gpt4 book ai didi

Javascript绘制图像函数失败

转载 作者:行者123 更新时间:2023-12-03 04:06:58 24 4
gpt4 key购买 nike

我已经尝试过绘制功能,但现在我要转向图像了,但我遇到了困难。这是代码:

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);

我确信这与文件名或任何东西无关,而且我看不出有任何问题,但鬼魂不会出现!有什么问题吗?

最佳答案

你需要在加载时绘制幽灵。所以,做一些像...

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>

关于Javascript绘制图像函数失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com