我试图在javascript中获取绘制到画布中的图像的图像数据,但下面的脚本在ctx.getImageData()
处无声地失败。控制台中不显示任何错误消息。
var image = new Image();
image.src = "https://www.example.com/7/44/35.png"
image.width = 256;
image.heigth = 256;
var canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, 256, 256);
var imageData = ctx.getImageData(0, 0, 256, 256);
console.log(imageData) //this is never called, no error is displayed in console
我做错了什么?
修改: 我不认为这是一个与CORS相关的问题,我在图像源的同一个域上运行脚本并且仍在静默运行
答案 0 :(得分:1)
做了一些调整以使其正常工作:
image.crossOrigin = "anonymous"
image.onload
和drawImage()
之前,使用ctx.getImageData()
事件等待图片加载。以下是一个例子:
var image = new Image();
image.crossOrigin = "anonymous";
image.src = "http://i.imgur.com/8B8ye29.jpg";
image.width = 400;
image.heigth = 400;
var canvas = document.createElement("canvas");
canvas.width = 400;
canvas.height = 400;
var ctx = canvas.getContext("2d");
image.onload = function() {
ctx.drawImage(image, 0, 0, 400, 400);
var imageData = ctx.getImageData(0, 0, 400, 400);
console.log(imageData.height);
}