简体   繁体   English

通过ajax将图像加载到画布中

[英]load an image via ajax into canvas

It relates to another question Cross Origin Resource Sharing Headers not working only for safari . 它涉及另一个问题,即跨源资源共享标头不仅仅适用于野生动物园

I am trying to load an image into canvas from s3. 我正在尝试将图像从s3加载到画布中。 Seems safari < 6.0 has a bug related to loading images via CORS. safari < 6.0似乎存在一个与通过CORS加载图像有关的错误。 So the canvas get tainted though the image has cors enabled. 因此,尽管图像已启用cors,但画布仍会受到污染。 So I was thinking if there is some way to make an ajax request and then load the response into a canvas ? 所以我在想是否有某种方法可以发出ajax请求,然后将响应加载到画布中?

Note : Ajax request works properly with CORS. 注意:Ajax请求可与CORS一起正常使用。 Just that while loading image safari doesn't respect the crossOrigin attribute and hence the request is made without cross-origin. 只是在加载图像Safari时不遵守crossOrigin属性,因此发出的请求没有交叉来源。

  • I have my images at s3 so there is no way to encode it to base64 and get it from amazon directly 我的图片在s3上,因此无法将其编码为base64并直接从Amazon获取
  • I am preferring not to set up a proxy at my domain for the image 我不希望在我的域中为该图像设置代理

some javascript 一些JavaScript

var img_location = "//temp_upload_test.s3.amazonaws.com/IMG_0222.JPG"
var img = new Image();

img.onload = function(){

    console.log("image loaded")
    EXIF.getData(img,function(){
        console.log("image data read");
        var orientation = EXIF.getTag(img,'Orientation');
        console.log("orientation"+orientation);
        load_image_into_canvas_with_orientation(img,orientation);
    })
    console.log("image loaded function complete");
}
img.crossOrigin = "anonymous";
$(img).attr("crossOrigin","anonymous");
img.src = img_location;

One way I am trying to approach the problem is make an xhr request to s3. 我尝试解决该问题的一种方法是向s3发出xhr请求。 get the image as BinaryFile and then decode it to base64 and use it as img's src . 将图像获取为BinaryFile ,然后将其解码为base64并将其用作img的src But while decoding I get a DOM exception not sure if the idea itself is wrong 但是在解码时我得到了DOM异常,不确定该想法本身是否错误

img.crossOrigin = "anonymous";

It does not works in all cases because of security issue. 由于安全问题,它并非在所有情况下都有效。

You can load any image in canvas by converting that image to base64 string and then bind to canvas. 您可以通过将图像转换为base64字符串然后绑定到画布来将其加载到画布中。

Example: 例:

<img src="www.example.com/name.png" alt="test" />

to

<img src="data:image/png;base64,vnaXYZetc..." alt="test" /> 

then load it to in canvas. 然后将其加载到画布中。

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM