Javascript drawImage函数失败

时间:2017-06-12 19:46:01

标签: javascript canvas drawimage

我玩过绘画功能,但现在我正在转向图像,我已经碰到了一堵砖墙。这是代码:

var x
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ghost = new Image();
ghost.src = "ghost.png"

window.setTimeout(x, 5000);


var drawIm = function (sprite) {
    ctx.save();
    ctx.translate(100, 100);
    ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
    ctx.restore();
};


drawIm(ghost);

我确定它与文件名或任何东西无关,我看不出任何问题,但鬼不会出现!有什么问题?

1 个答案:

答案 0 :(得分:1)

你需要在它加载时画出鬼。所以,做点什么......



var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ghost = new Image();

//ghost onload event
ghost.onload = function() {
   drawIm(ghost);
}

ghost.src = "https://lessonpix.com/drawings/2587/100x100/Happy+Ghost.png";

var drawIm = function(sprite) {
   ctx.save();
   ctx.translate(100, 100);
   ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
   ctx.restore();
};

<canvas id="canvas" width="200" height="200"></canvas>
&#13;
&#13;
&#13;