How to use Fabric.js to save a canvas as an image
17,470
Solution 1
The following must be true:
- Your cross-domain
<img>
elements must contain acrossorigin
attribute. - The server hosting the images must return an Access-Control-Allow-Origin header in the response with either a wildcard, or your specific domain as the value.
- The browser must support CORS on
HTMLMediaElement
s, specificallyHTMLImageElement
s. This is only currently possible in Chrome, Firefox, and Opera 15+
Solution 2
This works well for me
function convertToImagen() {
canvas.deactivateAll().renderAll();
window.open(canvas.toDataURL('png'));
}
Solution 3
As a side note, remember that if you're developing on your local computer rather on a server, you will probably see this security error message.
Related videos on Youtube
Author by
mheavers
Updated on September 15, 2022Comments
-
mheavers over 1 year
I have a Fabric.js prototype where people can load photos, text, and maps into the canvas. When they're done, I want them to be able to save the canvas as an image. I've tried using the standard:
canvasURL = canvas.toDataURL(); var image = new Image(); image.src = canvas.toDataURL("image/png"); $('#canvasContainer').replaceWith(image);
but it says that the canvas is
tainted
- I think because of the images (the method above works when it's just text). The error is:Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
I can use Fabric's built-in method to save as SVG:
var canvasSVG = canvas.toSVG(); $('#canvasContainer').replaceWith(canvasSVG);
But I'd rather have a PNG/JPG. Any ideas?
Here's the Fabric.js documentation on serialization of the canvas.
-
Ray Nicholus about 10 yearsNote: This might be possible as well in Safari 7 as well.
-
Ray Nicholus almost 10 yearsThis is potentially dangerous advice. There is no reason to make this a synchronous call. Doing so opens up the the possibility of locking up the entire browser if this request takes a noticeable amount of time. Please consider changing your answer.
-
melwyn pawar almost 10 yearsi have been working on an application where in images can be dragged and dropped from folders,browsers, or can be searched for from dropbox accounts or gdrives, i firstly identify the samedomain flag and pass the images for conversion if from a different domain, yes there is a average delay of 3.5 secs depending on the image size considering an average of 2mb with a download speed of 512kbps, but I also proportionately scale own the image to a reasonable size.This has worked well for me so far.please let me know your views
-
Ray Nicholus almost 10 yearsThe bottom line is, never use synchronous Ajax requests in the browser outside of web workers. Nothing you are doing requires a synchronous call.