You are trying to copy data from a un-parsed binary PNG file to the canvas which of course won't work as the PNG contains chunks and other data, and the image itself is compressed binary data which has to be deflated. Loading via AJAX won't parse the PNG, it will simply be treated as a raw binary file as any other file and the result will be random colored noise.
You have to load the PNG and use it as a source for an image element which will take care of parsing and deflating, then draw the image element to canvas (unless you want to parse the file manually, which is do-able).
You could simply load the image directly as you say, without the need for AJAX:
var img = new Image();
img.onload = function() {
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
// next step here...
};
img.src = url;
There is no difference between these methods in terms of getting the pixel data later - in both cases CORS requirements must be fulfilled.
However, if you for some reason absolutely need AJAX (which makes no sense as you would still have to pass it through an image element): load the image data as a Blob
instead of ArrayBuffer
, then create an object-URL for it which can be used as image source for an image element:
var xhr = new XMLHttpRequest();
xhr.open('GET', './ColorTable.PNG', true);
xhr.responseType = 'blob'; // we want a blob
xhr.onload = function(e) {
var url = URL.createObjectURL(this.response); // ! URL may need prefix
var img = new Image();
img.onload = function() {
URL.revokeObjectURL(this.src); // auto-revoke can be set in some browsers
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
};
img.src = url;
};
xhr.send();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…