微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何始终关注画布?

我一直在寻找这个论坛的解决方案,但还没有找到.无论我在哪里点击页面,我都需要始终关注画布元素.我有几个按钮,在我写的每个onclick事件中:
document.getElementById('canvas').focus();

这样做可以,但我认为这不是最好的做法.任何的想法?

解决方法

认情况下,Canvas元素不可聚焦.您需要先为它设置tabIndex.

document.querySelector("canvas").onblur = function() {
    var me = this;
    me.style.background = "red";
    setTimeout(function() {
        me.style.background = "transparent";
        me.focus();
    },500);
}
canvas {border:1px solid #000}
Click on canvas then outside - a blur event will be thrown coloring the background red for half a second:<br>
<canvas tabindex=0 ></canvas>

但是,我真的没有理由为什么你需要强制关注canvas元素.

如果你想捕获鼠标和键事件,有更好的方法来做到这一点,例如防止事件冒泡.强制关注还会阻止输入字段的工作,可访问性等.

以下是捕获鼠标移动和按键事件并将其重定向到画布使用的一种方法

示例“劫持”事件

var ctx = document.querySelector("canvas").getContext("2d");

// redirect events
window.addEventListener("mousemove",function(e) {
    var rect = ctx.canvas.getBoundingClientRect(),x = e.clientX - rect.left,y = e.clientY - rect.top;
  
  ctx.fillRect(x-2,y-2,4,4);
});

window.addEventListener("keydown",function(e) {
  e.preventDefault();
  ctx.fillText(e.keyCode,Math.random() * 300,Math.random() * 150);
});
html,body {width:100%;height:100%;margin:0;overflow:hidden}
canvas {border:1px solid #000}
<h1>Demo</h1>
<p>Active this window by clicking in it,then hit some keys and move mouse around</p>
<canvas tabindex=0></canvas>
<h2>End</h2>
<button>Test button</button>

原文地址:https://www.jb51.cc/js/157419.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐