有没有办法允许用户在div的顶部绘制并允许绘图浮动在顶部,但是对于下面的div仍然可以选择?
使用html5 canvas(react-sketch),你当然可以在div的页面顶部叠加一个canvas对象,但是底层div被(透明)画布覆盖,虽然可以查看,但是无法选择。
有什么简单的方法吗?
答案 0 :(得分:1)
这是可行的,但你会邀请一些我认为根本不值得的挑战。
示例:
var ctx = c.getContext("2d"), rect = c.getBoundingClientRect(), isDown = false;
c.width = rect.width;
c.height = rect.height;
// canvas interaction when no divs are in the way
window.onmouseup = window.onmousedown = function(e) {isDown = e.type === "mousedown"};
window.onmousemove = function(e) {
if (isDown) ctx.fillRect(e.clientX, e.clientY, 2, 2);
};

#c {
position:fixed;
left:0;
top:0;
width:100vw;
height:100vh;
pointer-events:none;
}
div {
padding:10px;
border:1px solid #999;
width:200px;
margin-bottom:9px;
}

<div>Hello</div>
<div>There</div>
<canvas id=c></canvas>
&#13;
正如您所看到的,当然,我们可以在画布下面进行交互并选择div,但我们仍在绘制画布等等。
如果我可以建议一种不同的方法,那就是有一个模式切换,这样当你使用UI中的开关/按钮激活交互模式时,只允许与画布交互,当然,在模式下反之亦然关掉了。
模式按钮可以附加到热键,鼠标中键等等。
var ctx = c.getContext("2d"), rect = c.getBoundingClientRect(), isDown = false;
var drawMode = false;
c.width = rect.width;
c.height = rect.height;
window.onmouseup = c.onmousedown = function(e) {isDown = e.type === "mousedown"};
// only draw if we are in interactive mode
c.onmousemove = function(e) {
if (drawMode && isDown) ctx.fillRect(e.clientX, e.clientY, 2, 2);
};
// toggle mode
document.querySelector("button").onclick = function() {
this.classList.toggle("selected");
c.classList.toggle("active");
drawMode = !drawMode;
};
&#13;
#c {
position:fixed;
left:0;
top:0;
width:100vw;
height:100vh;
pointer-events:none;
}
#c.active {
pointer-events:auto;
}
div {
padding:10px;
border:1px solid #999;
width:200px;
margin-bottom:9px;
}
button {
position:fixed;
right:7px;
top:7px;
opacity:0.5;
transition:opacity 0.2s;
background:#9f9;
border:1px solid #000;
padding:7px;
}
button:hover {opacity:1}
button.selected {background:#fc0}
&#13;
<div>Hello</div>
<div>There</div>
<canvas id=c></canvas>
<button>Interactive mode</button>
<p>Click button in upper right corner to activate interactive drawing on canvas</p>
&#13;