<template>
  <div class="imgCanvansDiv">
    <img
      :src="imageObj[index].path"
      :ref="'imgref' + index"
      :id="'img' + index"
    />

    <canvas
      :ref="'canvansref' + index"
      :id="'canvas_' + index"
      class="canvasAll"
    ></canvas>
  </div>
</template>
<script>
export default {
  props: {
    imageObj: {
      type: Array,
      default: () => [],
    },
    index: {
      type: Number,
      default: () => "",
    },
  },
  data() {
    return {
      textInfo: "",
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.drawlineListAll(this.imageObj);
    });
  },
  methods: {
    //绘制所有的图片告警区域
    drawlineListAll(val) {
      for (let i = 0; i < val.length; i++) {
        console.log(i);
        console.log(document.getElementById("canvas_" + i));
        console.log(document.getElementById("img" + i));
        this.canvas = document.getElementById("canvas_" + i);
        this.imgpic = document.getElementById("img" + i);
        this.textInfo = val[i].enname;
        console.log(this.textInfo);
        console.log(this.imgpic.offsetWidth);
        console.log(this.canvas);
        this.canvas.width = this.imgpic.offsetWidth; //设置画布大小
        this.canvas.height = this.imgpic.offsetHeight; //设置画布大小
        console.log(this.canvas.width, this.canvas.height);
        this.ctx = this.canvas.getContext("2d");
        this.ctx.beginPath();
        //设置线条颜色，必须放在绘制之前
        this.ctx.strokeStyle = "#ff0000";
        // 线宽设置，必须放在绘制之前
        this.ctx.lineWidth = 1;

        // 绘制矩形
        var scaleX = this.canvas.width / val[i].photoWidth, //this.iw图片的宽
          scaleY = this.canvas.height / val[i].photoHeight; //this.ih图片的高
        console.log(scaleX, scaleY);
        var top = val[i].x * scaleX,
          left = val[i].y * scaleY,
          width = val[i].width * scaleX,
          height = val[i].height * scaleY;
        console.log(top, left, width, height);
        // this.ctx.strokeStyle = "red"; //线的颜色
        this.ctx.strokeRect(top, left, width, height); //绘制路径矩形
        //this.ctx.strokeRect(val[i].x, val[i].y, val[i].width, val[i].height);
        this.ctx.font = "16px normal";
        this.ctx.fillStyle = "#ff0000";
        //this.ctx.fillText(this.textInfo, top, left + 24);
        //距离上面有空间
        if (left > 32) {
          this.ctx.fillText(this.textInfo, top, left - 4);
        } else if (this.canvas.height - left + height > 32) {
          this.ctx.fillText(this.textInfo, top, height - 4);
        }
        this.ctx.closePath();
        this.ctx.stroke();
      }
    },
  },
};
</script>
<style lang="less">
.imgCanvansDiv {
  width: 100%;
  height: 100%;
  position: relative;
  img {
    width: 100%;
    height: 100%;
  }
  .canvasAll {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    left: 0;
    top: 0;
    pointer-events: none;
  }
}
</style>
