【问题标题】:Sprites not showing on html5 canvas精灵未在 html5 画布上显示
【发布时间】:2017-09-29 17:28:25
【问题描述】:

我有一个基于图块的平台游戏,其中图块当前使用 fillRect 函数呈现在彩色矩形中。我有一个精灵表,我想用它来渲染矩形。每个图块和精灵的宽度和高度均为 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;
        }
    }

如有任何帮助,谢谢

【问题讨论】:

  • 你的 .src 链接到 HTML 而不是 IMG ibb.co/e5K5Qb
  • 哎呀,我需要一个在线的小提琴,它现在是一个 png,但它仍然无法正常工作
  • 你需要把图片的url改成https://image.ibb.co/hZe5Qb/levelOne.png然后注意:图片是异步加载的,所以当你尝试绘制它时,实际上还没有加载图片
  • 你的数学错了jsfiddle.net/LsLpyn8p/5试试这个:ctx.drawImage(spriteSheet, 0, 10, tileSize, tileSize, posX, posY, tileSize, tileSize);
  • 但如果我每秒裁剪图像 60 次,在我需要再次使用它之前它不会有机会加载

标签: javascript html canvas


【解决方案1】:

我假设您正在尝试放置图像的剪切块。

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

你的 SourceImage 的 X 坐标是 128。图像太小,没有这么多像素。

10开头,例如:

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

jsFiddle

Documentation

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.

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 2014-04-28
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 2013-02-13
    • 2020-03-23
    相关资源
    最近更新 更多