akifquddus
akifquddus

Reputation: 632

Export FabricJS canvas to PNG/JPG with Images in it

This is my code to export canavs to Image using FabricJS:

window.open(canvas.toDataURL( {format: 'jpeg' }));

Code to add images is below:

fabric.Image.fromURL('URL here', function(img) {
var oImg = img.set({ left: 50, top: 100,}).scale(0.5);
        canvas.add(oImg).renderAll();
        canvas.setActiveObject(oImg);
});

It works fine with Text and Shapes, but gives out of an .htm file when external images are added to the canvas.

No explicit errors, just the wrong output.

How can I fix this issue?

Upvotes: 0

Views: 4150

Answers (1)

Ben
Ben

Reputation: 979

To set the background use canvas.setBackgroundImage instead. You can provide a fabric image for it as the first argument, which, if loaded using the crossOrigin approach, should avoid the problem happening when you use a background.

fabric.Image.fromURL('http://lorempixel.com/g/400/200/', handleImage, {crossOrigin: 'anonymous'});

function handleImage(img) {
    canvas.setBackgroundImage(img);
    // do whatever extra needs to be done for the background
}

http://fabricjs.com/docs/fabric.Canvas.html

http://scanova.io/blog/engineering/2014/06/09/fabric-js-slow-rendering-issues-cors/

Upvotes: 4

Related Questions