How to keep the focus on a canvas always?

前端 未结 3 1699
醉话见心
醉话见心 2021-01-12 05:12

I\'ve been looking for a solution in this forum, but not found yet. I need to keep the focus on a canvas element always, no matter where i click on the page. I have several

3条回答
  •  爱一瞬间的悲伤
    2021-01-12 05:48

    Canvas elements are not focusable by default. You need to set a tabIndex for it first.

    Example

    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:

    However, I cannot really see any reason why you would need to force focus on the canvas element.

    If you want to catch mouse and key events there are better ways to do it by for example prevent an event from bubbling up. Forcing focus will also prevent input fields from working, accessibility and so forth.

    Here is one way you can catch mouse moves and key down events and redirect them to canvas use:

    Example "hijacking" events

    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}

    Demo

    Active this window by clicking in it, then hit some keys and move mouse around

    End

提交回复
热议问题