vue + canvas绘制背景图、矩形
最近有需求做图片人脸识别,在系统上传图片后,后台返回坐标将识别到的人脸画上矩形。效果图如下:实现过程:1、利用绘制canvas实例//html<canvas id='imgCanvas' ref='imgCanvas'></canvas>//jsthis.canvas = this.$refs.imgCanvas;this.canvas.height = this.$ref
·
- 最近有需求做图片人脸识别,在系统上传图片后,后台返回坐标将识别到的人脸画上矩形。
- 效果图如下:
实现过程:
1、利用绘制canvas实例
//html
<canvas id='imgCanvas' ref='imgCanvas'></canvas>
//js
this.canvas = this.$refs.imgCanvas;
this.canvas.height = this.$refs.picContainer.offsetHeight;
this.ctx = this.canvas.getContext("2d");
2、将图片绘制到canvas上
注意,我这里canvas的宽高是固定的,图片不进行拉伸,需要让图片自适应
// 绘制canvas图片
drawCanvas(){
var image = new Image()
image.src = this.bigImg;
image.onload = ()=>{
this.iw = image.width;
this.ih = image.height;
var local = this.calculate(this.iw, this.ih);//图片自适应canvas
this.canvas.width = local.pw;
this.canvas.height = local.ph
this.ctx.drawImage(image,0, 0, local.pw, local.ph); //表示x和y坐标
}
},
// 计算出图片画在canvas中的四个参数,图片自适应canvas
calculate(pw, ph) {
var w = this.$refs.picContainer1.offsetWidth,//获取元素的宽
h = this.$refs.picContainer.offsetHeight,
px = 0,
py = 0;
if(pw < w && ph < h){
px = 0.5 * w - 0.5 * pw;
py = 0.5 * h - 0.5 * ph;
}else if (ph / pw > h / w) {
var uu = ph;
ph = h
pw = pw * h / uu
px = 0.5 * w - 0.5 * pw;
} else {
var uu = pw;
pw = w;
ph = ph * pw / uu
py = 0.5 * h - 0.5 * ph;
}
return {px, py, pw, ph}
},
3、将图片上传后台,将返回的坐标绘制在canvas上。
由于图片是在canv上自适应的,后台返回是图片上的坐标,这里需要转换成canvas的坐标。
// 画矩形
drawRect(val){
// 绘制矩形
var x = this.canvas.width/this.iw,//this.iw图片的宽
y = this.canvas.height/this.ih;//this.ih图片的高
var top = val.location.top,left = val.location.left,width = val.location.width,height = val.location.height;
this.ctx.strokeStyle = "red"; //线的颜色
this.ctx.strokeRect(left*x, top*y, width*x, height*y); //绘制路径矩形
// 绘制文字
this.ctx.font = "18px bold";
this.ctx.fillStyle = "red";
this.ctx.textAlign = "center";
this.ctx.textBaseline = "middle";
this.ctx.fillText(val.name, left*x+18,top*y-18);
},
这个canvas使用只用了绘制图片和绘制矩形,许多canvas复杂的动画图形没有应用,比较简单。
更多推荐
已为社区贡献3条内容
所有评论(0)