如何使用Canvas在图片上绘制区域?
一. 首先,我们需要初始化三个canvas画布(初始化Canvas)
initCanvas() {// 初始化canvas画布let canvasWrap = document.getElementsByClassName("canvas-wrap");this.wrapWidth = canvasWrap[0].clientWidth;this.wrapHeight = canvasWrap[0].clientHeight;this.imgCanvas = document.getElementById("imgCanvas");this.imgCtx = this.imgCanvas.getContext("2d");// 绘制canvasthis.drawCanvas = document.getElementById("drawCanvas");this.drawCtx = this.drawCanvas.getContext("2d");// 保存绘制区域 saveCanvasthis.saveCanvas = document.getElementById("saveCanvas");this.saveCtx = this.saveCanvas.getContext("2d");
}
imgCanvas
用于绘制原始图片drawCanvas
用于临时绘制区域saveCanvas
用于保存最终绘制的区域
二. 计算并设置canvas的宽高比例,以适应图片尺寸
initImgCanvas() {// 计算宽高比let ww = this.wrapWidth; // 画布宽度let wh = this.wrapHeight; // 画布高度 let iw = this.imgWidth; // 图片宽度let ih = this.imgHeight; // 图片高度if (iw / ih < ww / wh) {// 以高为主this.ratio = ih / wh;this.canvasHeight = wh;this.canvasWidth = (wh * iw) / ih;} else {// 以宽为主 this.ratio = iw / ww;this.canvasWidth = ww;this.canvasHeight = (ww * ih) / iw;}// 初始化画布大小this.imgCanvas.width = this.canvasWidth;this.imgCanvas.height = this.canvasHeight;this.drawCanvas.width = this.canvasWidth; this.drawCanvas.height = this.canvasHeight;this.saveCanvas.width = this.canvasWidth;this.saveCanvas.height = this.canvasHeight;// 图片加载绘制let img = document.createElement("img");img.src = this.imgUrl;img.onload = () => {console.log("图片已加载");this.imgCtx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight);this.renderDatas(); // 渲染原有数据};
}
这里先计算画布和图片的宽高比,根据比例关系决定以宽为主还是以高为主进行等比缩放。然后设置三个canvas的宽高,并在图片加载完成后将其绘制到imgCanvas
上。renderDatas
函数用于渲染已有的绘制数据。
三. 绘制的主要逻辑
startDraw() {// 绘制区域if (this.isDrawing) return;this.isDrawing = true;// 绘制逻辑this.drawCanvas.addEventListener("click", this.drawImageClickFn);this.drawCanvas.addEventListener("dblclick", this.drawImageDblClickFn);this.drawCanvas.addEventListener("mousemove", this.drawImageMoveFn);
}