我正在尝试更改在线HTML5
Canvas Pacman游戏中的精灵。
目前,我试图更改原始图片: http://kasperbjerreskov.dk/games/pacman/sprites/spritesheet1.png(原创) spritesheet.png(已编辑)
但这似乎不起作用。
我在代码中发现了一些东西,看起来像是在绘制精灵,但我不知道该怎么做。
这是一个开源版本,可以找到:http://pacman.shaunew.com/redmine/projects/pacman/repository 仍然使用原始来源,新图像除外。
答案 0 :(得分:0)
你可以使用剪裁形式context.drawImage
从精灵表中删除任何精灵:
context.drawImage(
// from the spritesheet
spritesheet,
// go to x,y on the spritesheet and cut out a width x height sized subimage
spriteX, spriteY, spriteWidth, spriteHeight,
// and draw that subimage on the canvas at canvasX, canvasY
canvasX, canvasY, spriteWidth, spriteHeight
);
示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// define a few sprite's position on the spritesheet
var pacOpenRight={ x:20,y:20,width:20,height:20 };
var ghostRed={ x:40,y:80,width:20,height:20 };
var spritesheet=new Image();
spritesheet.onload=start;
spritesheet.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/PacmanSpritesheet.png";
function start(){
ctx.fillRect(0,0,cw,ch);
drawSprite(pacOpenRight,50,50);
drawSprite(ghostRed,70,50);
}
function drawSprite(spriteDef,canvasX,canvasY){
ctx.drawImage(
// from the spritesheet
spritesheet,
// go to x,y on the spritesheet and
// cut out a width x height sized subimage
spriteDef.x, spriteDef.y, spriteDef.width, spriteDef.height,
// and draw it on the canvas at x,y
canvasX, canvasY, spriteDef.width, spriteDef.height
);
}
<canvas id="canvas" width=300 height=300></canvas>