Joginder Sharma
Joginder Sharma

Reputation: 105

How reduce size of canvas image before send to server

I am using Fabric.js. When I try to send canvas image to server using canvas.toDataURL('image/png') it takes around 40 sec. I convert it to blob but it also take 25-30 seconds. When I reduce canvas size it reduces background image size but the object (text and images) appear outside the background image (reducing not proportional). How can I minimize the uploading time?

Upvotes: 2

Views: 3188

Answers (2)

Satendra
Satendra

Reputation: 6865

toDataURL

You can set format attribute to jpeg, This will instantly drop image size by 50%

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

If you want more compression you can set quality attribute to it.

canvas.toDataURL({
   'format':'jpeg'
   // default value of `quality` is 1 and varies from 0..1
   'quality': 0.5
});

Note: quality attribute only works for jpeg format

Upvotes: 0

user1693593
user1693593

Reputation:

You need to take a snapshot of the current canvas to a new canvas with the new size:

You could for example do this.

var fabricCanvas = document.getElementById('fcanvas');  //real ID here
var scaledCanvas = document.createElement('canvas');    //off-screen canvas

scaledCanvas.width = 400;  //size of new canvas, make sure they are proportional
scaledCanvas.height = 300; //compared to original canvas

// scale original image to new canvas
var ctx = scaledCanvas.getContext('2d');
ctx.drawImage(fabricCanvas, 0, 0, scaledCanvas.width, scaledCanvas.height);

//extract image
var data = scaledCanvas.toDataURL(); //no need to specify PNG as that's the def.

Now you can upload a reduced version of the canvas.

Upvotes: 3

Related Questions