Alex Alex - 10 months ago 52
Javascript Question

Resize canvas to bigger image and send it to the server

Hi I have an canvas on my web page. The problem is that the canvas is like 550x380 pixels and I need to export an image like A1 format, which is 9933x7016 pixels and then send it to the server. Is that possible at all?

Answer Source

You can resize the canvas by setting its width and height properties.

// ? is a Number < 32767
canvas.width = ?; 
canvas.height = ?;

But changing the canvas resolution may clear it. To ensure that you keep the image you need to create a new canvas.

var newCan = document.createElement("canvas");

Then set to the size you need.

newCan.width = ?
newCan.height = ?

Then copy the old canvas onto it.

var ctx1 = newCan.getContext("2d");

Changing the canvas from 550x380 pixels to 9933x7016 will only really be worth doing if you re render all the content, For that you will need to scale up.

// canvas is the old canvas (small)
var scaleX = newCan.width / canvas.width;
var scaleX = newCan.height / canvas.height;
// set scale on new canvas
ctx1.setTransform(scaleX, 0, 0, scaleY, 0, 0);

Then you can rerender the content at the higher resolution without changing you render values.

Also not many machines will not be able to handle a canvas that large, throwing either a "Out of memory error" or just crashing. If the machine has the memory and the browser tab is still running you will also on many machines have a very slow update when displaying the canvas. 9933x7016 requires close to 280Mbytes of GPU or CPU RAM to store. Even though the machine has that RAM it may not be available. So ensure you have a backup of any generated data that is required for the canvas content so the client can at least try again.