DrawImage 未在 canvas 中绘制

DrawImage is not drawing in a canvas

基本上我一直在尝试做的是制作一个循环,循环通过一吨(仅 36 atm)的瓷砖,并将它们按顺序放置。虽然该部分有效,但它实际上并没有加载图像和显示图像。

使用 console.log,我已将问题缩小到绘制图像的时间(或者至少我很确定这就是问题所在)。

我试过切换局部变量和全局变量,但似乎没有任何作用,而且我还切换了原来的变量:

ctx.drawImage(loadTile, tileToLoadX, tileToLoadY);

收件人:

loadTile.onload = function() {
ctx.drawImage(loadTile, tileToLoadX, tileToLoadY);
};"

正如许多人建议的那样处理类似的问题。

var canvas = document.getElementById("mapcanvas");
var ctx = canvas.getContext("2d");

GTH = 3000;
GTW = 3000;

tileCountX = 6;
tileCountY = 6;

mapWidth = tileCountX * GTW;
mapHeight = tileCountY * GTH;

function imageSearch() {
for (u=1; u < tileCountY + 1; u++) {
    for (i=1; i < tileCountX + 1;i++) {
    tileToLoad = "x" + i + "y" + u;
    tileToLoadX = i * GTW - GTW;
    tileToLoadY = u * GTH - GTH;
    console.log("Successfully found tile " + tileToLoad);
    loadImg();
    }
}
};
function loadImg() {
var loadTile = new Image();
loadTile.src = 'Top/x+y+/' + tileToLoad + ".png";
loadTile.onload = function() {
ctx.drawImage(loadTile, tileToLoadX, tileToLoadY);
};
console.log("Successfully loaded tile " + tileToLoad);
};

imageSearch();

另请注意,canvas 应该与图块大小相同,GTH 和 GTW 是所有图块的默认高度和宽度。

不胜感激!谢谢!

我对可能发生的事情有 2 个想法。

  1. 您的 src 路径不正确

loadTile.src = 'Top/x+y+/' + tileToLoad + ".png";

验证控制台中没有任何加载问题。

  1. 您在屏幕外绘制图像

你的canvas真的是18000像素宽吗?尝试 ctx.drawImage(loadTile, 0, 0);并查看图像是否绘制到 canvas.

备注

不要使用全局变量。 imageSearch() 很可能会在您的第一个图像加载之前完全执行。这将导致您的所有图块都绘制在同一位置,我相信您不希望这样。

在你的函数中

function loadImg() {
    var loadTile = new Image();
    loadTile.src = 'Top/x+y+/' + tileToLoad + ".png";
    loadTile.onload = function() {
        ctx.drawImage(loadTile, tileToLoadX, tileToLoadY);
    };
    console.log("Successfully loaded tile " + tileToLoad);
};

变量 tileToLoadtileToLoadXtileToLoadY 作为局部变量属于函数 imageSearch(),并且将是未定义的。

此外,在为图像变量分配 src 之前,需要设置 loadTile.onload 操作。

尝试进行以下更改。

function imageSearch() {
    for (u=1; u < tileCountY + 1; u++) {
        for (i=1; i < tileCountX + 1;i++) {
            tileToLoad = "x" + i + "y" + u;
            tileToLoadX = i * GTW - GTW;
            tileToLoadY = u * GTH - GTH;
            console.log("Successfully found tile " + tileToLoad);
            loadImg(tileToLoad,tileToLoadX,tileToLoadY); //send variables along
        }
    }
};

function loadImg(img,imgX,imgY) { //added new arguments for the function
    var loadTile = new Image();
    loadTile.onload = function() {
        ctx.drawImage(loadTile, imgX, imgY);
    };
    loadTile.src = 'Top/x+y+/' + img + ".png"; //moved this to after the onload.
    console.log("Successfully loaded tile " + img);
};