Sie können jeden Sprit vom spritesheet schneiden den Ausschnitt Form context.drawImage
Verwendung:
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
);
Beispiel Codes und eine Demo:
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>
Was meinst du mit "Sprites ändern"? Wenn Sie nur ein Sprite aus dem Spritesheet zeichnen wollen, können Sie die Clipping-Version von ['context.drawImage'] verwenden (http://stackoverflow.com/questions/21446087/using-a-sprite-sheet-with-multiple- Sprites/21461197 # 21461197). – markE
Ich möchte den Pacman Sprite zu einem Staubsauger und die Geister zu "Staubhasen" ändern – Kasperb29
Ich weiß nicht, Pacman, aber ich nehme an, Staubsauger und Staub-Hasen sind Sprites auf dem Spritesheet vorhanden. Zeichne deinen Staubsauger-Sprite und dein Staubhasen-Sprite aus dem Spritesheet mit der Clipping-Version von 'context.drawImage'. Ein Beispiel finden Sie in diesem vorherigen [Stackoverflow Q & A] (http://stackoverflow.com/questions/21446087/using-a-sprite-sheet-with-multiple-sprites/21461197#21461197). – markE