Reputation: 30188
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.
http://fabricjs.com/fabric-intro-part-3/#serialization
Upvotes: 7
Views: 18930
Reputation: 343
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.
Upvotes: 2
Reputation: 39
This works well for me
function convertToImagen() {
canvas.deactivateAll().renderAll();
window.open(canvas.toDataURL('png'));
}
Upvotes: 3
Reputation: 1816
I faced the same issue, solved it by first passing the image url in an ajax call to a php file that would convert the image and return a data url
<?php
$content=file_get_contents($_POST['imageurl']);
echo "data:image/png;base64,". base64_encode($content);
?>
make sure to set the async:false for the ajax call
you can use the returned data to create your image object and load it on canvas.
Upvotes: -2
Reputation: 19921
The following must be true:
<img>
elements must contain a crossorigin
attribute.HTMLMediaElement
s, specifically HTMLImageElement
s. This is only currently possible in Chrome, Firefox, and Opera 15+Upvotes: 4