我想在HTML画布上绘制一个选择矩形(通过鼠标拖放,就像MS Paint一样)。
下面的代码片段有效,但需要使用两个不同的画布。
问题:如何在单个画布上实现此操作,以便稍后可以更改画布的图像而不必删除选择矩形?
我们应该保留两个不同的画布吗(如果是这样,如何使#2完全覆盖第一个画布,而不使用absolute
定位)?
还是说可以通过单个画布以更简单的方式实现?(使用ctx.globalCompositeOperation = "source-over";
或类似方法)
var c1 = document.getElementById("c1"), c2 = document.getElementById("c2");
var ctx1 = c1.getContext("2d"), ctx2 = c2.getContext("2d");
ctx2.setLineDash([5, 5]);
var origin = null;
window.onload = () => { ctx1.drawImage(document.getElementById("img"), 0, 0); }
c1.onmousedown = e => { origin = {x: e.offsetX, y: e.offsetY}; };
window.onmouseup = e => { origin = null; };
c1.onmousemove = e => {
if (!!origin) {
ctx2.strokeStyle = "#ff0000";
ctx2.clearRect(0, 0, c2.width, c2.height);
ctx2.beginPath();
ctx2.rect(origin.x, origin.y, e.offsetX - origin.x, e.offsetY - origin.y);
ctx2.stroke();
}
};
#img { display: none; }
#c1 { border: 1px solid green; }
#c2 { border: 1px solid blue; }
<img id="img" src="https://i.imgur.com/okSIKkW.jpg">
<canvas id="c1" height="200" width="200"></canvas>
<canvas id="c2" height="200" width="200"></canvas>