here is my code,i want to move the picture(pic1) with the four arrow keyboards,draw some lines as background areas,and the pic move 1s a time,but i meet a problem that i can’t move the pic1,who can tell me why it’s doesn’t work
<script type="text/javascript">
var canvas = document.getElementById("painting");
//canvas.addEventListener("keydown", doKeyDown, true);
var context2D = canvas.getContext("2d");
var pic = new Image();
var pic1=new Image();
var X=0,Y=200;
var X1=200,Y1=200;
pic.src = "music.jpg";
pic1.src = "qingwa.jpg";
function drawline()
{
context2D.moveTo(0,100);
context2D.lineTo(35,100);
context2D.lineTo(35,60);
context2D.lineTo(85,60);
context2D.lineTo(85,100);
context2D.lineTo(155,100);
context2D.lineTo(155,60);
context2D.lineTo(205,60);
context2D.lineTo(205,100);
context2D.lineTo(275,100);
context2D.lineTo(275,60);
context2D.lineTo(325,60);
context2D.lineTo(325,100);
context2D.lineTo(395,100);
context2D.lineTo(395,60);
context2D.lineTo(445,60);
context2D.lineTo(445,100);
context2D.lineTo(515,100);
context2D.lineTo(515,60);
context2D.lineTo(565,60);
context2D.lineTo(565,100);
context2D.lineTo(600,100);
context2D.stroke();
}
function doKeyDown(e)
{
switch (e.keyCode)
{
// the up key
case 38:
Y1 = Y1 - 10;
break;
//the down key
case 40:
Y1 = Y1 + 10;
break;
//the left key
case 37:
X1 = X1 - 10;
break;
//the right key
case 39:
X1 = X1 + 10;
break;
}
}
function drawfrogger()
{
context2D.drawImage(pic1,X1,Y1);
}
function draw()
{
context2D.clearRect(0,0,600,600);
context2D.save();
context2D.drawImage(pic,X,Y);
drawfrogger();
drawline();
context2D.restore(); //绘制结束以后,恢复画笔状态
if(X>600)
X = 0;
X = X + 100;
}
setInterval(draw, 1000);
</script>
Only elements that can receive focus such as form inputs will generate key events. You have two options:
tabindexattribute to your<canvas>element to allow it to receive focus. A value of0will place the element in the default tab order (i.e. HTML source order). Here is article with some more detail.documentinstead. This has the disadvantage of capturing key events that originate anywhere in the document, not just the<canvas>element you’re interested in.