我有一大堆的畫布元素在我的HTML文件中像這樣:如何將焦點更改爲新的HTML5 Canvas元素?
<canvas id="one"></canvas>
<canvas id="two"></canvas>
我使用箭頭鍵來移動物體周圍#one
,但我想有一個對象「出現」在#two
時它在#one
上遇到了一個點,例如x=150
和y=55
。 我嘗試使用jQuery focus()
方法時觸發該座標,但對象留在#one
。有什麼建議麼?
我有一大堆的畫布元素在我的HTML文件中像這樣:如何將焦點更改爲新的HTML5 Canvas元素?
<canvas id="one"></canvas>
<canvas id="two"></canvas>
我使用箭頭鍵來移動物體周圍#one
,但我想有一個對象「出現」在#two
時它在#one
上遇到了一個點,例如x=150
和y=55
。 我嘗試使用jQuery focus()
方法時觸發該座標,但對象留在#one
。有什麼建議麼?
要使畫布元素焦點的,還爲此能夠捕捉到關鍵的招,只需添加一個tabIndex
屬性的元素:
現在,您可以TAB,並將事件偵聽器直接綁定到畫布元素。
在處理程序中,您只需根據所需的任何標準繪製到所需的畫布。
例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);
}
canvas {border:1px solid #999;margin:0 2px 2px 0; display:inline-block}
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
<canvas></canvas>
而不是改變時座標打擊的重點,我認爲你需要改變<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借用代碼。將圓圈拖到頂部畫布的左上角,它應該出現在下方的畫布中。
有作爲焦點用於此目的的畫布上沒有這樣的事情。
您的兩個畫布需要偵聽按鍵,而您的代碼需要決定在哪個畫布上繪製什麼。
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>
當然,這可以優化將不會對每個節拍都重畫的畫布,但你的想法。