如何确保 canvas 上图像的加载顺序
how to make assure the load order of images on canvas
我有两张图片要画 canvas。
我想确保 A 显示在 B 上。
var Apic = new Image();
var Bpic = new Image();
Apic.src = "Apic.png";
Bpic.src = "Bpic.png";
// I want to add z-index to
Apic.style = "z-index:1;";
Bpic.style = "z-index:2;";
Apic.onload = function() {
context.drawImage(Apic 0,0);
};
Bpic.onload = function() {
context.drawImage(Bpic,0,0);
};
但是还是不行,有什么好的解决办法吗??
在 Ken Fyrstenberg 的帮助下,我已经解决了这样的问题。
每次在Apic上绘制Bpic
虽然不是什么好办法,但暂时可以解决问题
Apic.onload = function() {
context.drawImage(Apic 0,0);
context.drawImage(Bpic,0,0);
};
Bpic.onload = function() {
context.drawImage(Bpic,0,0);
};
只需将 url 放入数组即可。以与并行数组相同的顺序创建图像元素。这将保持秩序紧张。然后您需要计算成功的加载次数,以便我们确定我们拥有所需的所有图像数据:
var urls = ["Apic.png", "Bpic.png"]; // url and order
var pics = []; // holds the image elements
var count = urls.length; // number of images to load
for(var i = 0, url; url = urls[i++];) { // share onload handler
var pic = new Image(); // create a new image
pics.push(pic); // store in array
pic.onload = loadCounter; // set load handler (also add for error)
pic.src = url; // set url to start loading
}
function loadCounter() {
count--;
if (!count) { // when done we can draw the images in order:
for(var i = 0, pic; pic = pics[i++];) {
context.drawImage(pic, 0, 0);
}
}
};
我有两张图片要画 canvas。
我想确保 A 显示在 B 上。
var Apic = new Image();
var Bpic = new Image();
Apic.src = "Apic.png";
Bpic.src = "Bpic.png";
// I want to add z-index to
Apic.style = "z-index:1;";
Bpic.style = "z-index:2;";
Apic.onload = function() {
context.drawImage(Apic 0,0);
};
Bpic.onload = function() {
context.drawImage(Bpic,0,0);
};
但是还是不行,有什么好的解决办法吗??
在 Ken Fyrstenberg 的帮助下,我已经解决了这样的问题。
每次在Apic上绘制Bpic
虽然不是什么好办法,但暂时可以解决问题
Apic.onload = function() {
context.drawImage(Apic 0,0);
context.drawImage(Bpic,0,0);
};
Bpic.onload = function() {
context.drawImage(Bpic,0,0);
};
只需将 url 放入数组即可。以与并行数组相同的顺序创建图像元素。这将保持秩序紧张。然后您需要计算成功的加载次数,以便我们确定我们拥有所需的所有图像数据:
var urls = ["Apic.png", "Bpic.png"]; // url and order
var pics = []; // holds the image elements
var count = urls.length; // number of images to load
for(var i = 0, url; url = urls[i++];) { // share onload handler
var pic = new Image(); // create a new image
pics.push(pic); // store in array
pic.onload = loadCounter; // set load handler (also add for error)
pic.src = url; // set url to start loading
}
function loadCounter() {
count--;
if (!count) { // when done we can draw the images in order:
for(var i = 0, pic; pic = pics[i++];) {
context.drawImage(pic, 0, 0);
}
}
};