javascript - 有什么方法可以让 html5 canvas 触摸到下面的项目吗?

标签 javascript html html5-canvas

有什么方法可以允许用户在 div 板上绘图并允许绘图 float 在顶部,但下面的 div 仍然可以选择?

使用html5 canvas(react-sketch),你当然可以在div的页面顶部叠加一个canvas对象,但是随后底层的div被(透明)canvas覆盖,虽然可以查看,但无法选择。

有什么简单的方法可以解决这个问题吗?

最佳答案

这是可行的,但您会带来一些挑战,在我看来,这些挑战根本不值得。

示例:

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>

正如您所看到的,当然,我们可以交互并选择 Canvas 下方的 div,但我们仍然在 Canvas 上绘图等等。

如果我可以建议一种不同的方法,那就是有一个模式开关,这样当您使用 UI 中的开关/按钮激活交互模式时,只允许与 Canvas 交互,当然,反之亦然。已关闭。

模式按钮可以附加到热键、鼠标中键等。

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;
};
#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}
<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>

关于javascript - 有什么方法可以让 html5 canvas 触摸到下面的项目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293567/

相关文章:

javascript - 变量从 PHP 转换成 jQuery 形成链接

html - 在行下方添加空格和边框

html - bootstrap 折叠 div 显示 1 隐藏 1

javascript - 使标签贴在 div 顶部

javascript - 为什么我必须使用 this.canvas?

javascript - 在 HTML5 Canvas 上迭代时获取 X 和 Y 像素坐标 getImageData

javascript - 缩放后获取 Canvas 上鼠标的相对位置

javascript - 创建一个正则表达式以用相同字符替换字符串的每个匹配字符

javascript - 不使用<table>标签制作表结构?

javascript - 不能多次更改 html 元素的不透明度