javascript - 从图像元素动态创建 Canvas 元素

标签 javascript arrays dom html5-canvas

我试图循环遍历页面上的所有 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/

相关文章:

javascript - 在模块中使用 Facebook JS SDK (webpack)

javascript - <td> 内的动态 anchor 标记

javascript - 知道为什么 adonis 迁移命令不起作用吗?

ios - 数组 'contains()' 检查未能检测到舍入值

javascript - 在YouTube视频页面上,如何通过javascript检查视频当前是否正在播放广告或实际视频?

javascript 动态脚本创建与脚本延迟

javascript - 不压缩javascript和CSS对客户端处理有什么影响

ios - 使用 Realm 快速保存图像数组

javascript - 重复函数 JavaScript

javascript - 使用 javascript 将 img 元素添加到 div