- 论坛徽章:
- 0
|
为什么下面代码中pic1图片出现了一下就消失,我打算用a,s,w,d四个键来控制pic1这张图片上下移动
<!DOCTYPE html>
<html>
<head>
<title>frogger</title>
</head>
<body>
<canvas id="painting" width="600" height="600" style="border: 1px dashed grey;">
</canvas>
< > ress TAB to begin, W, A, S, D keys to move</P>
<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.onload = function()
{
context2D.drawImage(pic1,X1,Y1);
}
pic1.src = "qingwa.jpg";
function doKeyDown(e)
{
// the W key
if(e.keyCode == 87)
{
clearCanvas();
Y1 = Y1 - 10;
context2D.drawImage(pic1,X1,Y1);
}
//the s key
if(e.keyCode == 83)
{
clearCanvas();
Y1 = Y1 + 10;
context2D.drawImage(pic1,X1,Y1);
}
//the a key
if(e.keyCode == 65)
{
clearCanvas()
X1 = X1 - 10;
context2D.drawImage(pic1,X1,Y1);
}
//the d key
if(e.keyCode == 6
{
clearCanvas()
X1 = X1 + 10;
context2D.drawImage(pic1,X1,Y1);
}
}
function clearCanvas()
{
canvas.width = canvas.width;
}
function draw()
{
context2D.clearRect(0,0,600,600);
context2D.save();
context2D.drawImage(pic,X,Y);
context2D.restore(); //绘制结束以后,恢复画笔状态
if(X>600)
X = 0;
X = X + 100;
}
setInterval(draw, 1000);
</script>
</body>
</html> |
|