Andrew Simpson
Andrew Simpson

Reputation: 7324

Can I load an image directly on to a canvas without using the image element

I am using the canvas control. I use the image element to draw the image to the canvas on the image onload event.

I am looking to see if I can improve the performance by not loading into the image element first and directly locad the image to the canavs.

can this be done?

This is my current code:

desktopImage.src = "/Media/FrameHandler.ashx?camIndex=" + camIndex;

desktopImage.onload = function () {
    ctxLiveViews.drawImage(desktopImage, 0, 0);
}

I have been playing around with this code but the blob requires an ArrayBuffer:

var blob = new Blob('data:image/jpeg;base64,' + jpeg, { type: "image/jpeg" });
var url = (URL || webkitURL).createObjectURL(blob);
(URL || webkitURL).revokeObjectURL(url); 

AMENDED CODE:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1/Media/FrameHandler.ashx?camIndex=' + camIndex, true);                     
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    var uInt8Array = new Uint8ClampedArray(this.response);
    imageData[camIndex].data.set(uInt8Array);
    ctxLiveViews[camIndex].putImageData(imageData[camIndex], 0, 0);
};
xhr.send();

Generic Handler:

public void ProcessRequest(HttpContext context)
{
    context.Response.AddHeader("Access-Control-Allow-Origin", "*");
    context.Response.ContentType = "image/jpeg";
    var camIndex = Convert.ToInt16(context.Request.QueryString["camIndex"]);
    context.Response.BinaryWrite( Shared.Feeder[camIndex].JpegData);           
}

Image OutPut:

enter image description here

Upvotes: 2

Views: 1698

Answers (1)

Yangguang
Yangguang

Reputation: 1785

Here is a method to directly load the image data to canvas, without considering the data is right be drew:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
var imageData = ctx.getImageData(0, 0, 256, 256);

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://fiddle.jshell.net/img/logo.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    var uInt8Array = new Uint8ClampedArray(this.response);
    imageData.data.set(uInt8Array);
    ctx.putImageData(imageData, 0, 0);
};

xhr.send();

jsfiddle

If you want to get the blob:

xhr.onload = function (e) {
    var uInt8Array = new Uint8Array(this.response);
    var blob = new Blob([ uInt8Array ], { type: "image/png" });
    var urlCreator = window.URL || window.webkitURL;
    var url = urlCreator.createObjectURL(blob);       
}; 

Upvotes: 1

Related Questions