I want to read a image from my own server using Ajax and render that to Canvas.
Now I know that this can be achieved using normal image tags and canvas draw like shown below :
<img id="myImage" src="./ColorTable.PNG" style="display:none;"/>
var img = document.getElementById('myImage');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
But I don't want to use it and instead was looking if we can read the file using a Ajax call for the image src location and then render it to canvas , but for me it just shows a wrong image : Here's what I did :
var xhr = new XMLHttpRequest();
xhr.open('GET', './ColorTable.PNG', true);
xhr.responseType = 'arrayBuffer';
xhr.onload = function(e) {
var data = this.response;
var buf = new ArrayBuffer(data.length);
var bufView = new Uint8Array(buf);
for (var index = 0; index < data.length; index++) {
bufView[index] = data.charCodeAt(index);
}
//initialize and get context and then render the image
var ctx = canvas.getContext('2d');
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (var i = 0 ; i < imgData.data.byteLength; i++) {
imgData.data[i] = bufView[i];
imgData.data[i++] = bufView[i];
imgData.data[i++] = bufView[i];
imgData.data[i++] = 255;
}
ctx.putImageData(imgData, 0, 0);
};
xhr.send();
But the second approach doesn't work for me as the image that is rendered is a wrong one . Can anybody help?