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

<script>
export default {
  props: {
    imgUrl: String
  },
  data() {
    return {
      canvasContext: null
    };
  },
  watch: {
    imgUrl: {
      handler() {
        this.drawImage();
      },
      immediate: true
    }
  },
  mounted() {
    this.initCanvas();
  },
  methods: {
   initCanvas() {
         const query = uni.createSelectorQuery().in(this);
         query.select('#myCanvas')
           .fields({ node: true, size: true })
           .exec((res) => {
             if (!res[0]) return;
             
             this.canvas = res[0].node;
             this.ctx = res[0].node.getContext('2d');
             this.canvasContext = this.ctx; // 保存上下文
             
             const dpr = uni.getSystemInfoSync().pixelRatio;
             this.canvas.width = res[0].width * dpr;
             this.canvas.height = res[0].height * dpr;
             this.ctx.scale(dpr, dpr);
             
             // 如果已有图片URL，立即绘制
             if (this.imgUrl) {
               this.drawImage();
             }
           });
       },
    
    async drawImage() {
      if (!this.ctx || !this.imgUrl) return;
      
      try {
        const image = await this.loadImage(this.imgUrl);
        this.clearCanvas();
        this.ctx.drawImage(image, 0, 0, 800, 600);
      } catch (e) {
        console.error("图片加载失败:", e);
        this.clearCanvas();
        this.ctx.fillStyle = '#f0f0f0';
        this.ctx.fillRect(0, 0, 1000, 800);
        this.ctx.fillStyle = '#999';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        this.ctx.fillText('图片加载失败', 150, 100);
      }
    },
    
    clearCanvas() {
			if (this.ctx) {
				this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
			}
		},
    loadImage(src) {
			return new Promise((resolve, reject) => {
				const image = this.canvas.createImage();
				image.src = src;
				
				image.onload = () => resolve(image);
				image.onerror = (err) => {
					console.error('图片加载错误', err);
					reject(err);
				};
			});
		}
  }
}
</script>