简体   繁体   中英

How do I resize the canvas content and get the resized (and compressed) image base64 data?

I am playing with the canvas and have created a drawing demo.

Now I can draw stuff on that canvas and get the data with .toDataURL() .

Everything goes perfect except for the data of the image is too big. And I just only need a very small version of the drawing.

Is there any way (even possible) that I can resize the canvas to a smaller version and load the resized image data? It's kinda like to compress the image with pure JavaScript.

For instance, I let the user to draw on a 1000px * 500px canvas and resize it to 50px * 25px. The resized base64 data would be very small and convenient for further network-transfer. That's what I want to have.

You let your user draw on the big canvas, then you draw the big canvas as an image on the small canvas. Finally you get the small canvas image as a data URI.

The small canvas doesn't have to be attached to the DOM.

let bigCanvas_img = document.querySelector("bigCanvas");
smallCanvas_ctx.drawImage(bigCanvas_img,0,0,smallCanvas_w,smallCanvas_h);


let url = smallCanvas.toDataURL();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM