document.activeElement不适用于canvas元素

时间:2018-03-13 10:53:25

标签: javascript html5

我有一个从emscripten端口渲染的WebGL画布。我正在尝试为它创建一个ghetto暂停屏幕,但由于某种原因,我无法获取document.activeElement来检测画布。从我读过的所有内容来看,它应该有效。

var testCanvas = document.getElementById("canvas")

function testFocus() {
if (document.activeElement === testCanvas[0]) {
console.log('canvas has focus');
} else {
console.log('canvas not focused');
}};
window.setInterval(testFocus, 1000);

JSFiddle replicating the problem

1 个答案:

答案 0 :(得分:-1)

您的代码中有两个错误

1,tabindex不是标签索引

第二次if (document.activeElement === testCanvas) // not testCanvas[0]

<canvas id="canvas" width="578" height="480" tabindex="1">  
</canvas>

var testCanvas = document.getElementById("canvas")
var testSpan = document.getElementById("plswork")
var context = canvas.getContext('2d');
var imageObj = new Image();

imageObj.onload = function() {
  context.drawImage(imageObj, 69, 50);
};
imageObj.src = 'https://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';

function testFocus() {
  if (document.activeElement === testCanvas) {
    console.log('canvas has focus');
  } else {
    console.log('canvas not focused');
  }
};
window.setInterval(testFocus, 1000);

小提琴:https://jsfiddle.net/42x34k68/6/