Reputation: 534
I am using Parse.com to store image files for a mobile application. The images are correctly stored and retrieved. The problem is when the image is added to a FabricJS canvas, the canvas is marked "tainted" and hence cannot be saved (using canvas.toDataURL).
I tried adding the "crossOrigin" option:
fabric.Image.fromURL( ... parse.com url .. , function(img) {
img.set({
left: 10,
top: 10
});
$scope.canvas.add(img);
$scope.canvas.setActiveObject(img);
}, { "crossOrigin" : "anonymous" } );
However this returned the error:
Image from origin 'http://files.parsetfss.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.
I cannot find a way to add the header above in Parse.com. I also cannot implement a proxy server since that is the whole point of using Parse.com.
I would appreciate your help, thank you.
Upvotes: 2
Views: 2082
Reputation: 534
Found a solution for this using Parse.com "Cloud Code". Steps are the following:
// These two lines are required to initialize Express in Cloud Code. var express = require('express'); var app = express(); // Global app configuration section app.set('views', 'cloud/views'); // Specify the folder to find templates app.set('view engine', 'ejs'); // Set the template engine app.use(express.bodyParser()); // Middleware for reading request body // // Example request: // http://files.parsetfss.com/XXX/YYY // app.get('/images/:tag1/:tag2', function(req, res) { Parse.Cloud.httpRequest({ url: 'http://files.parsetfss.com/' + req.params.tag1 + "/" + req.params.tag2, success: function(httpResponse) { // add CORS headers res.set("Access-Control-Allow-Origin", "*"); res.set("Access-Control-Allow-Headers", "X-Requested-With"); res.set('Access-Control-Allow-Headers', 'Content-Type'); res.send(httpResponse.buffer); }, error: function(err) { console.log(err); res.send('Error finding file'); } }); }); // Attach the Express app to Cloud Code. app.listen();
More details on setup Cloud Code on Parse.com are found here: https://parse.com/docs/js/guide#cloud-code
var url = <originalimageurl>; url = url.replace("http://files.parsetfss.com/", "http:\/\/<parsecom-domain>.parseapp.com\/images\/"); fabric.Image.fromURL(url, function(img) { img.set({ left: 10, top: 10 }); $scope.canvas.add(img); $scope.canvas.setActiveObject(img); }, { "crossOrigin" : "anonymous" } );
Replace <originalimageurl>
with the original image url stored in Parse.com.
Replace <parsecom-domain>
with your subdomain in Parse.com.
This will work since client (FabricJS) and proxy server (Parse.com CloudCode) supports CORS. Image created will no longer be considered Cross Origin thus canvas will not be tainted. Ultimately, canvas can now be saved!
I hope this helps someone else. Cheers.
Upvotes: 1