<template>
  <view>
    <canvas 
      id="myCanvas" 
      canvas-id="myCanvas" 
      type="2d" 
      style="width: 300px; height: 200px; border: 1px solid #eee;"
    ></canvas>
  </view>
</template>

<script>
export default {
  onReady() {
    this.drawImageOnCanvas();
  },
  methods: {
    drawImageOnCanvas() {
      // 获取Canvas节点
      const query = uni.createSelectorQuery().in(this);
      query.select('#myCanvas')
        .fields({ node: true, size: true })
        .exec(async (res) => {
          if (!res[0]) return;
          
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = uni.getSystemInfoSync().pixelRatio;
          this.canvas = canvas
          // 适配高清屏
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);

          // 加载图片
          try {
            const image = await this.loadImage('https://assets.tech.troyrc.com/sx25/images/background/odertupian.png');
            ctx.drawImage(image, 0, 0, 300, 200);
          } catch (e) {
            console.error("图片加载失败:", e);
            // 可选：绘制错误提示
            ctx.fillStyle = '#f0f0f0';
            ctx.fillRect(0, 0, 300, 200);
            ctx.fillStyle = '#999';
            ctx.textAlign = 'center';
            ctx.fillText('图片加载失败', 150, 100);
          }
        });
    },
    
    loadImage(src) {
      return new Promise((resolve, reject) => {
        const image = this.canvas.createImage();
        image.onload = () => resolve(image);
        image.onerror = reject;
        image.src = src;
      });
    }
  }
}
</script>