我需要用对象创建一个游戏。我试图将我的Link对象绘制到画布上,但由于某种原因它无法工作。我已经尝试过在这个问题的其他答案中描述的方法。我不明白为什么图像不会在画布上显示!这是我的代码(编辑到相关位)。
HTML
<script src='animateLink.js'></script>
<script>
//canvas variables
var canvas, ctx;
//key control variables
document.addEventListener("keyup", keyUpHandler);
document.addEventListener("keydown", keyDownHandler);
var leftKey, upKey, rightKey, downKey;
leftKey=false;
upKey=false;
rightKey=false;
downKey=false;
//Link variables
var link = new Link('../image_files/link_left.png',200,200,19,27,0);
//main animation functions
function initialize() {
canvas = document.getElementById('hello');
ctx = canvas.getContext('2d');
update();
}
function update() {
if(leftKey && link.linkX>0) {
link.linkX--;
link.frameX++;
link.src='../image_files/link_left.png';
}
else if(upKey && link.linkY<0) {
link.linkY--;
link.frameX++;
link.src='../image_files/link_up.png';
}
else if(rightKey && (link.linkX+link.frameW)>canvas.width) {
link.linkX++;
link.frameX++;
link.src='../image_files/link_right.png';
}
else if(downKey) { //probably won't use
link.linkY++;
link.frameX++;
link.src='../image_files/link_down2.png';
}
if(link.frameX>15) {
link.frameX=0;
}
draw();
requestAnimationFrame(update);
}
function draw() {
clearRect();
link.sketch();
}
document.write(link.toString());
function clearRect() {
ctx.clearRect(0,0,canvas.width,canvas.height);
}
//control functions
function keyDownHandler(e) { //SET TO BOOLEAN VALUES NOT STRINGS
switch(e.keyCode) {
case 37: leftKey=true; break;
case 38: upKey=true; break;
case 39: rightKey=true; break;
case 40: downKey=true; break;
}
}
function keyUpHandler(e) {
switch(e.keyCode) {
case 37: leftKey=false; break;
case 38: upKey=false; break;
case 39: rightKey=false; break;
case 40: downKey=false; break;
}
}
</script>
<body onload='initialize()'>
<canvas id='hello' width='1424px' height='810px'></canvas>
</body>
JS
//animated objects
//use frameW/H/X
function Link(src, linkX, linkY, frameW, frameH, frameX) {
//this.x=x?x:10;
//src entry will equal path to image file
this.src=src?src:'../image_files/link_left.png';
this.linkX=linkX;
this.linkY=linkY;
this.frameW=frameW;
this.frameH=frameH;
this.frameX=frameX;
}
Link.prototype.toString = function() {
return("("+this.src+","+this.linkX+","+this.linkY+","+this.frameW+","+this.frameH+","+this.frameX+")");
};
Link.prototype.sketch = function(ctx) { //(ctx)
var img = new Image();
/*img.onload = function() {
//ctx.drawImage(img, this.linkX, this.linkY, this.frameW, this.frameH);
ctx.drawImage(img, //image
display.linkX, //frameX
display.linkY, //frameY
display.frameW, //frameW
display.frameH, //frameH
display.linkX, //imageX
display.linkY, //imageY
display.frameW, //imageW
display.frameH); //imageH
}*/
img.onload = function() {
context.drawImage(img,this.linkX, this.linkY, this.linkW, this.linkH);
};
img.src = this.src;
};