Javascript 未在html5画布上显示精灵

Javascript 未在html5画布上显示精灵,javascript,html,canvas,Javascript,Html,Canvas,我有一个基于tile的平台游戏,其中tile当前使用fillRect函数渲染为彩色矩形。我有一个精灵表,我想用它来渲染矩形。每个瓷砖和精灵的宽度和高度为32像素。我知道我需要一个加载功能时,croping一个图像,但我不知道它应该去哪里,因为我需要作物和绘制精灵每秒60帧。这是我的小提琴- 或以下代码: var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d');

我有一个基于tile的平台游戏,其中tile当前使用fillRect函数渲染为彩色矩形。我有一个精灵表,我想用它来渲染矩形。每个瓷砖和精灵的宽度和高度为32像素。我知道我需要一个加载功能时,croping一个图像,但我不知道它应该去哪里,因为我需要作物和绘制精灵每秒60帧。这是我的小提琴-

或以下代码:

        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;
        }
    }
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
var宽度=6;
var高度=3;
var tileSize=32;
var计数器=0;
var playerUp=false;
设置间隔(gameLoop,1000/30);
函数gameLoop(){
ctx.fillStyle=“白色”;
ctx.fillRect(0,0,canvas.width,canvas.height);
对于(变量y=0;y

感谢您的帮助

我想您是在尝试放置图像的剪切部分

您指向的是
4*tileSize
,在本例中为4*32=128

源映像的X坐标为128。图像太小,没有这么多像素

10
开始,例如:

ctx.drawImage(spriteSheet, 0, 10, tileSize, tileSize, posX, posY, tileSize, tileSize);


你的.src链接到HTML不是IMG oops我需要一个在线的fiddle,它现在是png,但仍然不起作用你需要将图像url更改为
https://image.ibb.co/hZe5Qb/levelOne.png
然后注意:图像正在异步加载,所以当您尝试绘制它时,实际上没有加载图像是的您的数学错误尝试以下操作:
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.