如何使用AJAX读取图像文件并渲染到Canvas? [英] How to read a image file using AJAX and render to Canvas?

查看:146
本文介绍了如何使用AJAX读取图像文件并渲染到Canvas?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Ajax从自己的服务器读取图像并将其渲染到Canvas.

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

但是我不想使用它,而是在寻找是否可以使用Ajax调用读取图像src位置的文件,然后将其渲染到画布上,但是对我来说,它只是显示了错误的图像: 这就是我所做的:

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?

推荐答案

您正在尝试将数据从未解析的二进制PNG文件复制到画布,这当然不起作用,因为PNG包含块和其他数据,图像本身是压缩的二进制数据,必须压缩.通过AJAX加载不会解析PNG,它会像其他任何文件一样被视为原始二进制文件,并且结果将是随机的彩色噪声.

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.

您必须加载PNG并将其用作图像元素的源,它将负责解析和缩小,然后将图像元素绘制到画布上(除非您要手动解析文件,即可做).

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

您可以按照说明直接加载图像,而无需AJAX:

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;

在稍后获取像素数据方面,这两种方法没有区别-在两种情况下都必须满足CORS要求.

There is no difference between these methods in terms of getting the pixel data later - in both cases CORS requirements must be fulfilled.

但是,如果出于某种原因您绝对需要AJAX(这与您必须通过图像元素传递 still 毫无意义):将图像数据加载为Blob而不是ArrayBuffer,然后为其创建一个对象URL,该URL可用作图像元素的图像源:

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

这篇关于如何使用AJAX读取图像文件并渲染到Canvas?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆