我玩过绘画功能,但现在我正在转向图像,我已经碰到了一堵砖墙。这是代码:
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);
我确定它与文件名或任何东西无关,我看不出任何问题,但鬼不会出现!有什么问题?
答案 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;