0

I have been trying to figure out how I could resize the canvas contents to get roughly a 100x100 thumbnail and upload it to the server. I would like to keep my existing canvas in its current size, because all these actions have to be invisible to the user.

I know I can get the contents in the current size of the canvas by using toDataURL, but how could I resize it and then upload to the server?

var image = canvas.toDataURL("image/png");
Firze
  • 3,939
  • 6
  • 48
  • 61

2 Answers2

1

You can create canvas in your JS script (without appending it to DOM), then draw on it your content from working canvas (your image), resize it in context of your temp canvas ( Post about resizing in canvas ). And only then do canvas.toDataURL("image/png"); to get resized image. Then you send it as base64 string and save on your server as png file.

Community
  • 1
  • 1
freele
  • 142
  • 7
0

Thanks to Alexander Kremenets I managed to put together the code I needed. I used the Hermite resize from the question Alexander linked. Also combined code from other questions coming up with this:

var originalCanvas = document.getElementById("c");
// Create canvas for resizing
var resizeCanvas = document.createElement("canvas");
resizeCanvas.height = originalCanvas.height;
resizeCanvas.width = originalCanvas.width;

var resizeCtx = resizeCanvas.getContext('2d');
// Put original canvas contents to the resizing canvas
resizeCtx.drawImage(originalCanvas, 0, 0);

// Resize using Hermite resampling
resampleHermite(resizeCanvas, resizeCanvas.width, resizeCanvas.height, 150, 90);

// Use the resized image to do what you want
var image = resizeCanvas.toDataURL("image/png");
Community
  • 1
  • 1
Firze
  • 3,939
  • 6
  • 48
  • 61