如何将焦点更改为新的HTML5 Canvas元素?

时间:2015-05-14 21:34:38

标签: javascript jquery html5 canvas

我的html文件中有一堆画布元素,如下所示:

   <canvas id="one"></canvas>
   <canvas id="two"></canvas>

我使用箭头键在#one周围移动一个物体,但我希望有一个物体&#34;出现&#34;在#two点击#one上的点时,例如x=150y=55。 我尝试在触发该坐标时使用jQuery focus()方法,但该对象保留在#one中。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

要使canvas元素具有焦点,并且因此能够捕获键击,只需在元素中添加tabIndex属性:

  

现在你可以在元素之间 TAB 并直接将事件监听器绑定到canvas元素。

在处理程序内部,您只需根据所需的标准绘制到所需的画布。

实施例

&#13;
&#13;
var canvases = document.querySelectorAll("canvas"),
    i = 0; 

while(canvas = canvases[i++]) {
  canvas.width = 200;
  canvas.tabIndex = 0;
  canvas.addEventListener("keyup", process);
}

function process(e) {
  var ctx = this.getContext("2d");
  ctx.clearRect(0, 0, 200, 150);
  ctx.fillText("KEY HERE: " + e.keyCode, 10, 10);
}
&#13;
canvas {border:1px solid #999;margin:0 2px 2px 0; display:inline-block}
&#13;
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我认为您需要更改您要绘制的<canvas>元素(以及相关的上下文),而不是更改焦点,例如:

    var theCanvas = document.getElementById("one");
    var context = theCanvas.getContext("2d");

    ... your canvas drawing code here ...

    if (posX < 150 && posY < 55) {
        //clear the top canvas
        context.clearRect(0, 0, theCanvas.width, theCanvas.height);
        // switch to the second canvas
        theCanvas = document.getElementById("two");
        context = theCanvas.getContext("2d");
    }

Here's a fiddle借用rectangleworld.com的代码。将圆圈拖动到顶部画布的左上角,它应显示在下部画布中。

JSFiddle

答案 2 :(得分:0)

为此目的,没有专注于画布的事情。

你的两个画布都需要听按键,而你的代码需要决定在哪个画布上画画。

var canvas1 = document.getElementById("one");
var context1 = canvas1.getContext("2d");
var canvas2 = document.getElementById("two");
var context2 = canvas2.getContext("2d");

canvas1.width = canvas1.height = canvas2.width = canvas2.height = 50;

var obj = {x: 5, y: 5, w: 5};

function draw() {
  canvas1.width = canvas2.width = canvas2.width;
  context1.beginPath();
  context1.rect(obj.x, obj.y, obj.w, obj.w);
  context1.fillStyle = 'green';
  context1.fill();
  context2.beginPath();
  context2.rect(obj.x - canvas1.width, obj.y, obj.w, obj.w);
  context2.fillStyle = 'blue';
  context2.fill();
}

window.addEventListener('keydown', function() {
  if(++obj.x > canvas1.width + canvas2.width) obj.x = 5;  
  draw();
});

draw();
canvas {border: 1px solid black; margin: 10px;}
<canvas id="one"></canvas>
 <canvas id="two"></canvas>
<p>Click inside this window to get focus and then <br>press any key to move the object to the right</p>

当然,这可以优化,不会在每个刻度上重绘两个画布,但你明白了。