<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>
canvas给图片画框框
于 2021-08-17 18:55:49 首次发布