我可以直接将图像加载到画布上而不使用图像元素

我可以直接将图像加载到画布上而不使用图像元素

问题描述:

我正在使用画布控件。
我使用image元素将图像绘制到图像onload事件的画布上。

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

我希望看看我是否可以提高性能首先加载到图像元素并直接将图像定位到canavs。

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.

可以这样做吗?

这是我目前的代码:

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

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

我一直在玩这个代码,但blob需要一个ArrayBuffer:

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); 

修改后的代码:

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:

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:

Image OutPut:

这是一种直接将图像数据加载到画布的方法,不考虑数据是否正确:

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

如果你想获得 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);       
};