我有一个基于平铺的平台游戏,其中使用fillRect函数将切片呈现为彩色矩形。我有一个spritesheet,我想用它来渲染矩形。每个瓷砖和精灵的宽度和高度均为32像素。我知道在裁剪图像时我需要一个加载功能,但我不确定它应该去哪里,因为我需要裁剪并每秒画60帧精灵。继承人我的js小提琴 - https://jsfiddle.net/LsLpyn8p/4/
或以下代码:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = 6;
var height = 3;
var tileSize = 32;
var counter = 0;
var playerUp = false;
setInterval(gameLoop, 1000 / 30);
function gameLoop() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
posX = (x * tileSize) + 1 * x;
posY = (y * tileSize) + 1 * y;
// ctx.fillStyle = "green";
// ctx.fillRect(posX, posY, tileSize, tileSize);
var spriteSheet = new Image();
spriteSheet.src = 'https://pasteboard.co/GMAwgYX.png';
ctx.drawImage(spriteSheet, 0, 4 * tileSize, tileSize, tileSize, posX, posY, tileSize, tileSize);
}
}
ctx.fillStyle = "red";
ctx.fillRect(50, counter, tileSize, tileSize);
if (playerUp == true) {
counter--;
} else {
counter++;
}
if (counter == 100) {
playerUp = true;
} else if (counter == 0) {
playerUp = false;
}
}
感谢任何帮助
答案 0 :(得分:0)
我假设您正在尝试放置图像的剪切片段。
你指的是4 * tileSize
,在这种情况下它是4 * 32 = 128。
SourceImage的X坐标是128.图像太小,没有这么多像素。
以10
开头,例如:
ctx.drawImage(spriteSheet, 0, 10, tileSize, tileSize, posX, posY, tileSize, tileSize);
void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
sx
The X coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context.
sy
The Y coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context.