简体   繁体   English

HTML5 Canvas,Tileset 不会显示

[英]HTML5 Canvas, Tileset won't show up

My tileset won't show up.我的图块集不会出现。 What is the problem?问题是什么?

Here is a code:这是一个代码:

<!DOCTYPE html>
<html>

<head>
    <style>
    body {
        margin: 0px;
        padding: 0px;
    }

    #mapa {
        border: solid 1px;
    }
    </style>
</head>

<body> <canvas id="mapa" height="500px" width="500px"></canvas>
    <script>
    var canvas = document.getElementById('mapa');
    var ctx = canvas.getContext('2d');
    var trawa = new Image();
    trawa.src = "trawa.png";
    var mapa = [
        [0, 0, 0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0, 0, 0]
    ];
    var posX = 0;
    var posY = 0;
    for (var x = 0; x < mapa.length; x++) {
        for (var y = 0; y < mapa[x].length; y++) {
            if (mapa[x][y] == 0) {
                ctx.drawImage(trawa, posX, posY, 32, 32);
            }
            posX += 50;
        }
        posX = 0;
        posY += 50;
    }
    </script>
</body>

</html>

The problem here is that the image isn't loaded yet when you try to draw it, what you need to do is to wait until it is loaded.这里的问题是当您尝试绘制图像时尚未加载图像,您需要做的是等到它加载。

For that you can use trawa.onload as following:为此,您可以使用trawa.onload如下:

 <!DOCTYPE html> <html> <head> <style> body { margin: 0px; padding: 0px; } #mapa { border: solid 1px; } </style> </head> <body> <canvas id = "mapa" height = "500px" width= "500px"></canvas> <script> var canvas = document.getElementById('mapa'); var ctx = canvas.getContext('2d'); var trawa = new Image(); trawa.src = "trawa.png"; var mapa = [ [0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0] ]; var posX = 0; var posY = 0; trawa.onload = function (){ for (var x = 0; x < mapa.length; x++){ for (var y = 0; y < mapa[x].length; y++) { if (mapa[x][y] == 0) { ctx.drawImage(trawa, posX, posY, 32,32); } posX+=50; } posX = 0; posY+=50; } } </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM