如何通过拖放在 HTML 画布上绘制选择矩形?

Bas*_*asj 6 html javascript drag-and-drop selection html5-canvas

我想在 HTML 画布上绘制一个选择矩形(使用鼠标拖放,如使用 MS Paint)。

在此输入图像描述

以下代码片段可以工作,但使用两个不同的画布。

问题:如何在单个画布上执行此操作,以便以后可以更改画布的图像照片而无需删除选择矩形?

我们是否应该保留 2 个不同的画布(如果是这样,如何将 #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(); 
    } 
};
Run Code Online (Sandbox Code Playgroud)
#img { display: none; }
#c1 { border: 1px solid green; }
#c2 { border: 1px solid blue; }
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Bas*_*asj 1

可能有一个更好的解决方案,具有一个单层<canvas>和多个层(如果是这样,请随时发布另一个答案),但我最终使用了一种类似于html5 - canvas 元素 -具有 2 个画布覆盖的多个层的方法:

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); }
c2.onmousedown = e => { origin = {x: e.offsetX, y: e.offsetY}; };
window.onmouseup = e => { origin = null; };
c2.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(); 
    } 
};
Run Code Online (Sandbox Code Playgroud)
#img { display: none; }
#canvas-container { position: relative; }
canvas { position: absolute; left: 0; top: 0; }
#c1 { z-index: 0; }
#c2 { z-index: 1; }
Run Code Online (Sandbox Code Playgroud)
<img id="img" src="https://i.imgur.com/okSIKkW.jpg">
<div id="canvas-container">
<canvas id="c1" height="200" width="200"></canvas>
<canvas id="c2" height="200" width="200"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)