gpt4 book ai didi

javascript - 函数对象无法将图像从 Canvas 绘制到图像

转载 作者:行者123 更新时间:2023-11-27 23:22:55 25 4
gpt4 key购买 nike

标题措辞不佳,但无法简洁地描述问题。我正在将图像绘制到动态创建的 Canvas 的 2D 上下文中。然后,上下文的数据通过 toDataURL 保存到图像中,然后在每一帧上绘制。下面的代码是精简的,我将在上下文中绘制多个图像,而不仅仅是一个;这就是我保存到图像的原因。我只会一次绘制图像的一部分,但图像保持不变,所以我认为这是最好的方法,如果有替代方案,我会很乐意接受这些作为答案。

简而言之:在一个图像上绘制许多图像。图像的一部分绘制每一帧。下面的代码有效:

var picture = new Image();
picture.src = "images/tilesheet.png";
var canvas = document.getElementById("background");
var context = canvas.getContext("2d");
function generate(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = canvas.width;
ctx.canvas.height = canvas.height;
ctx.fillStyle = "red";
ctx.rect (0, 0, 40, 40);
ctx.fill();
ctx.drawImage(picture,0,0);
image = new Image();
image.src = ctx.canvas.toDataURL("image/png");
}
function draw(){
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0,0,100,100,0,0,100,100);
}
function play(){
generate();
setInterval(function(){draw();}, 0.0333);
}
window.onload = function(){
if(picture.complete)play();
else picture.onload = play;
}
<canvas id="background"></canvas>
然而这并没有:
window.Game = {};
canvas = document.getElementById("background");
var tilesheet = new Image();
tilesheet.src = "images/tilesheet.png";
(function(){
function Map(){
this.width = 2736;
this.height = 2736;
this.image = null;
}
Map.prototype.generate = function(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = this.width;
ctx.canvas.height = this.height;
ctx.fillStyle = "red";
ctx.rect (0, 0, 40, 40);
ctx.fill();
ctx.drawImage(tilesheet,0,0);
this.image = new Image();
this.image.setAttribute('crossOrigin', 'anonymous');
this.image.src = ctx.canvas.toDataURL("image/png");
}
Map.prototype.draw = function(context){
context.drawImage(this.image, 0,0, context.canvas.height, context.canvas.height, 0, 0, context.canvas.height, context.canvas.height);
}
Game.Map = Map;
})();
(function(){
var room = new Game.Map();
room.generate();
var draw = function(){
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
room.draw(canvas.getContext("2d"));
}
Game.play = function(){setInterval(function(){draw();}, 0.0333);}
})();
window.onload = function(){
if(tilesheet.complete)Game.play();
else tilesheet.onload = Game.play;
}
<canvas id="background"></canvas>

因此,问题似乎在于我正在使用函数对象,但我不确定。我究竟做错了什么?调试控制台中没有错误。

最佳答案

这两个有不同的执行顺序。

第一个:

  1. ...
  2. 附加image.onload
    1. 调用generate()
    2. ...

第二个:

  1. ...
  2. 调用generate()
  3. 附加image.onload
    1. ...

这就是它不起作用的原因 - generate() 期望加载图像,但是第二种情况的顺序不能保证它。

而不是

...
room.generate();
...
Game.play = function(){setInterval(function(){draw();}, 0.0333);}

这样做

...
Game.play = function(){
room.generate();
setInterval(function(){draw();}, 0.0333);
}

关于javascript - 函数对象无法将图像从 Canvas 绘制到图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35223076/

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