我想使用 XMLHttpRequest 加载 png 文件,然后使用响应在画布对象中设置图像数据,从而完全消除对 Image 对象的需要并直接访问 ImageData。到目前为止,我的代码如下所示:
var xhr = new XMLHttpRequest();
var context = document.createElement("canvas").getContext("2d"); // the context for the image we are loading
var display = document.getElementById("display").getContext("2d"); // the context of the canvas element in the html document
function load(event) {
var imagedata = context.createImageData(64, 64); // 64 = w, h of image
imagedata.data.set(new Uint8ClampedArray(this.response)); // the response of the load event
context.putImageData(imagedata,0,0); // put the image data at the top left corner of the canvas
display.drawImage(context.canvas, 0, 0, 64, 64, 0, 0, 64, 64); // draws a bunch of jumbled up pixels from my image in the top of my display canvas
}
xhr.addEventListener("load", load);
xhr.open("GET", "myimage.png");
xhr.responseType = "arraybuffer";
xhr.send(null);
我在这里做错了什么?将响应中的 ArrayBuffer 转换为 Uint8ClampedArray 是否有问题?我应该使用不同的数组类型吗?是 XMLHttpRequest 吗?这可能吗?