黑色帆布而不是图像

时间:2017-09-24 19:32:34

标签: javascript canvas

我的画布有问题。比如说,1/10时间我在黑色方块而不是我的图像上。我的代码如下,如何修改它以避免这种黑色显示?

<canvas id="Canvas" width="954" height="267"></canvas>

<script>

var canvas = document.getElementById('Canvas');
var context = canvas.getContext("2d");

// Map sprite
var mapSprite = new Image();
mapSprite.src = 'image.png';

var main = function () {
    draw();
};

var draw = function () {
    // Clear Canvas
    context.fillStyle = "#000";
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Draw diagramme
    context.drawImage(mapSprite, 0, 0, 954, 267);
}

main();
</script>

编辑1:全功能抽奖:

 var draw = function () {
    // Clear Canvas
    context.fillStyle = "#000";
    context.fillRect(0, 0, canvas.width, canvas.height);

    // Draw diagramme
    context.drawImage(mapSprite, 0, 0, nextWidth, nextHeight);

    //draw all precedent cross
    cross = new Image();
    cross.src = "cross.png";

    for (var i = 0; i < array_x.length; i++) {
    context.drawImage(cross, array_x[i], array_y[i], 10, 10);
    }
}

1 个答案:

答案 0 :(得分:1)

我相信您要等到图像加载完毕。

替换:

main();

使用:

mapSprite.addEventListener('load', main);