canvas给图片画框框

<template>
  <div class="item-img">
    <canvas id="myCanvas" width="1280" height="650">
      Your browser does not support the HTML5 canvas tag.
    </canvas>
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
//src为图片路径,gtcoord为标注框:[[x,y,w,h],[x,y,w,h]......], 起点与宽高确认一个框的位置
  props: ["src", "gtcoord", "dtcoord"],
  mounted() {
    this.imgURL = this.src;
    this.queryCanvasInfo();
  },
  methods: {
    //获取canvasdom节点
    queryCanvasInfo() {
      (this.c = document.getElementById("myCanvas")),
        (this.ctx = this.c.getContext("2d"));
      this.img = new Image();
      this.img.src = this.imgURL;
      this.createCanvasImg();
    },
    //创建图片画布
    createCanvasImg() {
    //   this.imgX = this.c.width / 2; //拖拽的X轴值
    //   this.imgY = this.c.height / 2; //拖拽的Y轴值
      let img = this.img;
      img.src = this.imgURL; //更换图片
      img.onload = () => {
        //图片加载时
        this.ctx.clearRect(0, 0, this.c.width, this.c.height); //清空这个范围的画布
        let a = img.width / img.height; //计算原始图片的宽高比例
        console.log(img.width, img.height, 999);
        if (img.width > img.height) {
          //当图片宽度大于高度则写死宽度按高度调整比例
          this.maxW = this.c.width; //最大宽度要等于画布的宽度
          this.maxH = this.maxW / a;
        } else {
          //相反
          (this.maxH = this.c.height), (this.maxW = this.maxH * a);
        }
         this.times = this.img.width / this.maxW; //计算原图与canvas的比例
        this.canvasInfo(); //重新绘制图片
      };
    },
    //绘制图片
    canvasInfo() {
      let w = this.maxW, //计算缩放的宽度
        h = this.maxH; //计算缩放的高度
      this.ctx.drawImage(
        this.img, //图片实例
       //   0,
       // 0, //x轴y轴的边距
        (this.c.width - w) / 2,
        (this.c.height - h) / 2, //x轴y轴的边距
        w,
        h //图片的宽高
      );
      this.canvasRect( this.dtcoord,"dt");
      this.canvasRect( this.gtcoord,"gt");
    },
    //标注框绘制
    canvasRect(list,txt) {
      list.forEach((item) => {
        if (!item) return;
        let ary = item,
          x = Number(ary[0]) / this.times,
          y = Number(ary[1]) / this.times,
          w = Number(ary[2]) / this.times,
          h = Number(ary[3])/ this.times;   
        this.ctx.lineWidth = "1"; //框的粗细
        if(txt=="gt"){
             this.ctx.strokeStyle = "yellow"; //gt选中的标注框为红色
        }else{
            this.ctx.strokeStyle = "red"; //dt选中的标注框为红色
        }  
       //开始绘制
        this.ctx.strokeRect(x, y, w, h);
      });
    },
  },
};
</script>
<style lang="less" scoped>
.item-img {
 text-align: center;
}
</style>
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值