场景:图片是后端返回的,同时返回集合点,
需求:将图片显示出来,并将点连线行程闭合的多边形展示在图片上
完整代码:
getData(){
let ths = this;
let canvas = this.$refs.canvasImg;
let ctx = canvas.getContext("2d");
let img = new Image();
img.src = require("../../../assets/lufei.jpeg");
img.width = 640;
img.height = 360;
let [width, height] = [img.width, img.height];
canvas.width = width;
canvas.height = height;
//显示图片
img.onload = function () {
//显示图片
ctx.drawImage(img, 0, 0, width, height);
//显示图片上的点
ths.initCanvas();
};
},
initCanvas(){
this.$nextTick(() => {
let canvas = this.$refs.canvasImg;
let ctx = canvas.getContext("2d");
//画线
ctx.beginPath();
let sceneBox = [{ x: 20, y: 10 },{ x: 350, y: 10 }, { x: 550, y: 160 },{ x: 450, y: 340 }, ];
sceneBox.forEach((item) => {
ctx.lineTo(item.x, item.y);
});
ctx.closePath();
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctx.closePath();
ctx.stroke();
});
}
遇到的问题:
1、图片显示不出来:
如果加载是的本地图片,需要用require引入
如果是线上图片,直接将图片地址赋值给img.src
2、图片上的点不出来
在使用img.onload()方法内,先绘制图片,紧接着调取绘制点的方法;
最初线不出来时的写法如下:
//显示图片
img.onload = function () {
//显示图片
ctx.drawImage(img, 0, 0, width, height);
};
//显示图片上的点
this.initCanvas();
后来将this.initCanvas();方法写在onloa内部会报错,this.initCanvas is not a function;此报错是this指向问题,所以在该方法中改变this:let ths = this;
画点的方法
moveStroke(point, context, color) {
context.beginPath();
console.warn("point.x, point.y", point.x, point.y);
context.moveTo(point.x, point.y);
//开始写字
context.lineTo(point.x, point.y);
context.strokeStyle = color;
context.lineWidth = 6;
context.lineCap = "round";
context.lineJoin = "round";
context.stroke();
},
//调用
let canvas = this.$refs.canvasImg;
let ctx = canvas.getContext('2d');
let sceneBox = [ { x: 20, y: 10 }, { x: 350, y: 10 },{ x: 550, y: 160 }, { x: 450, y: 340 },];
this.moveStroke1(sceneBox , ctx, 'green');