我试图循环遍历页面上的所有 img 标签,并为每个 img 动态创建一个 canvas 元素(这样我就可以使用 JavaScript 修改像素值)。但是,尽管我的代码当前正在将 Canvas 添加到页面,但它们仍然是空白的。我不知道这是否是我使用drawImage()函数的方式,代码结构的一些更大的问题或者完全是其他什么问题?
var images = [], canvas = [], context = [];
function init() {
var images = document.getElementsByTagName('img');
// Create a canvas for each image...
for(var i = 0; i < images.length; i++) {
canvas[i] = document.createElement('canvas');
context[i] = canvas[i].getContext('2d');
context[i].drawImage(images[i], 0, 0);
document.body.appendChild(canvas[i]);
}
}
document.addEventListener('DOMContentLoaded', init);
最佳答案
您可以在此处阅读:https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
您正在绘制已卸载的图像。您应该等待整个页面加载,或者向每个图像添加一个事件监听器,以便在加载图像时绘制其 Canvas 。我将选择第二个,因此图像会立即创建,而不是在加载所有样式表和所有内容之后。
var images = [], canvas = [], context = [];
function init() {
var images = document.getElementsByTagName('img');
// Create a canvas for each image...
for(var i = 0; i < images.length; i++) {
images[i].addEventListener("load", (function(i) {
canvas[i] = document.createElement('canvas');
context[i] = canvas[i].getContext('2d');
context[i].drawImage(images[i], 0, 0);
document.body.appendChild(canvas[i]);
}).bind(null, i)); // Bind to contextualize the variable so don't changes before the event is called because of the loop. As others may think, `i` is not overwritten by the event parameter, so this bind is safe.
}
}
document.addEventListener('DOMContentLoaded', init);
关于javascript - 从图像元素动态创建 Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761680/