Cross-origin Image fabric JS

Satendra Rai
ITNEXT
Published in
2 min readFeb 20, 2018

--

www.rockwellcollins.com

A mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.

Click here to share this article on LinkedIn »

Accessing image context data on chrome throws this error when image has a cross origin. Unable to get image data from canvas because the canvas has been tainted by cross-origin data.

To get around this using fabric js, Here I am sharing mainly three ways.

Set crossOrigin to anonymous

You will have to set a flag CrossOrigin in fabric that tells it to allow images from unknown origin. Setting this is easy.

fabric.Image.fromURL( URL, 
function (img) {
canvas.add(img);
canvas.renderAll();
},{ crossOrigin: 'anonymous', ... }
);

Use fabric.util.loadImage

You don’t need to set crossOrigin, when using loadImage, this method handle CORS implicitly.

fabric.util.loadImage(URL, 
function (img) {
var fab_image = new fabric.Image(img);
canvas.add(fab_image);
canvas.renderAll();
},{left:0, top:0, ... });
});

Use Proxy Image loading

This means always render image from same domain you are on.

For that I have created a Django view, that will read image from cross domain, write it on a temp file, and response with image data.

You can adopt the same approach with rails, php, java .. as well.

import requests
import tempfile
from django.http.response import HttpResponse
def proxy_image(request):
image = requests.get(request.GET['url'], stream=True)

# Was the request OK?
if image.status_code != requests.codes.ok:
return ""

# Create a temporary file
lf = tempfile.NamedTemporaryFile()

# Read the streamed image in sections
for block in image.iter_content(1024 * 8):
# If no more file then stop
if not block:
break

# Write image block to temporary file
lf.write(block)
lf.seek(0)
image_data = lf.read()
lf.close()

return HttpResponse(image_data, content_type="image/jpg")

Now the image URL will look something like

GET: http://yourdomain.com/proxy_image?url=<Cross domain image url>

var URL = 'http://yourdomain.com/proxy_image?url=http://crossdomain.com/image.jpg';fabric.Image.fromURL( URL, 
function (img) {
canvas.add(img);
canvas.renderAll();
},{}
);

So whenever you have to render cross domain image just make GET request to proxy_image with query parameter url

If you are using AWS s3 bucket to store your media files then refer How to fix AWS S3 Chrome and Safari CORS errors on images for troubleshooting.

(Help others to find my article on Medium by giving it 👏🏽 below.)

--

--