How to keep the focus on a canvas always?

前端 未结 3 1681
醉话见心
醉话见心 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:<br>
    <canvas tabindex=0 ></canvas>

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

    0 讨论(0)
  • 2021-01-12 05:48

    using jQuery , you can use trigger()

    $("#canvas").trigger("click");
    
    0 讨论(0)
  • 2021-01-12 05:52

    What about this (using jQuery):

    $('#canvas').focus().blur(function() {
        $('#canvas').focus();
    });
    

    The idea is to give it the focus back every time it loses it (blur).

    I made an example (with a textbox which is basically the same) here: http://jsfiddle.net/thepeak/j02vyryf/

    0 讨论(0)
提交回复
热议问题