在从 url 加载到图像对象时按特定顺序将图像绘制到 canvas
draw image to canvas in particular order while loading from url to image object
我正在尝试使用 Javascript 将多个图像绘制到 HTML Canvas 元素。图像存储为 URL,然后分配给 javascript 图像对象的 src。问题是图像需要按特定顺序加载。到目前为止,这是我的代码:
var canvas = document.getElementById("render");
var context = canvas.getContext("2d");
var src = ["image.png","image.png","image.png","image.png"];
var image = [new Image,new Image,new Image,new Image,];
for (var i =0;i<image.length;i++) {
image[i].onload = function() {
context.drawImage(image[i],0,0,canvas.width,canvas.height);
}
image[i].src=src[i];
}
我认为问题出在 image.onload 函数上,因为它正在等待图像加载,并且稍后添加的图像有机会在前一个图像之前加载。但是我不确定。
首选纯js,但不强制。
您需要将 load
侦听器与绘图分离。现在,您会在图像加载后立即绘图。在 Promise
and use Promise.all()
中包装加载图像。这将允许您以任意顺序加载所有图像,但以您指定的相同顺序呈现给您。
/**
* Promisify loading an image
* @param {String} imagePath The web location of the image
* @returns {Promise} A Promise that will resolve to an Image
*/
function loadImage(imagePath) {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener("load", () => {
resolve(image);
});
image.addEventListener("error", (err) => {
reject(err);
});
image.src = imagePath;
});
}
var canvas = document.getElementById("render"),
context = canvas.getContext("2d"),
imageSources = ["image.png", "image.png", "image.png", "image.png"];
Promise
.all(imageSources.map(i => loadImage(i)))
.then((images) => {
images.forEach((image) => {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
});
}).catch((err) => {
console.error(err);
});
我正在尝试使用 Javascript 将多个图像绘制到 HTML Canvas 元素。图像存储为 URL,然后分配给 javascript 图像对象的 src。问题是图像需要按特定顺序加载。到目前为止,这是我的代码:
var canvas = document.getElementById("render");
var context = canvas.getContext("2d");
var src = ["image.png","image.png","image.png","image.png"];
var image = [new Image,new Image,new Image,new Image,];
for (var i =0;i<image.length;i++) {
image[i].onload = function() {
context.drawImage(image[i],0,0,canvas.width,canvas.height);
}
image[i].src=src[i];
}
我认为问题出在 image.onload 函数上,因为它正在等待图像加载,并且稍后添加的图像有机会在前一个图像之前加载。但是我不确定。
首选纯js,但不强制。
您需要将 load
侦听器与绘图分离。现在,您会在图像加载后立即绘图。在 Promise
and use Promise.all()
中包装加载图像。这将允许您以任意顺序加载所有图像,但以您指定的相同顺序呈现给您。
/**
* Promisify loading an image
* @param {String} imagePath The web location of the image
* @returns {Promise} A Promise that will resolve to an Image
*/
function loadImage(imagePath) {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener("load", () => {
resolve(image);
});
image.addEventListener("error", (err) => {
reject(err);
});
image.src = imagePath;
});
}
var canvas = document.getElementById("render"),
context = canvas.getContext("2d"),
imageSources = ["image.png", "image.png", "image.png", "image.png"];
Promise
.all(imageSources.map(i => loadImage(i)))
.then((images) => {
images.forEach((image) => {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
});
}).catch((err) => {
console.error(err);
});