Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize the canvas output image to a specific size (width/height)

I have a big canvas (5000x5000) and I want to take a picture of it and create a thumbnail on client side. I can capture the image using canvas.toDataURL but how do i re-size it? Do i have to create an new $("<canvas></canvas>") element and then put that image inside and run the canvas2.toDataURL(); Can anyone help me with this? I can't get my head around it how to do it.

var canvas = document.getElementById("main");
var ctx = canvas.getContext("2d");
var tumbnail64 = null;
var image = new Image();
image.src = canvas.toDataURL();
image.onload = function() {

    $c2 = $("<canvas></canvas>");
    $c2[0].width=100;
    $c2[0].height=100;
    $c2[0].getContext("2d");
    $c2[0].drawImage(image, 0, 0,100,100);
    tumbnail64 = $c2[0].toDataURL();
};
like image 788
Kivylius Avatar asked May 05 '14 20:05

Kivylius


People also ask

How do you resize canvas on canvas?

With the Select and Move Tool, click the canvas size label or border to select the canvas. Click the canvas border handles to resize the canvas dynamically. When you drag the border handles without using any keyboard modifiers, the canvas resizes non-uniformly. Hold Shift to constrain the resize proportions.

How do I change the width and height of a dynamic canvas?

To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas . height = 500 ; drawScreen ();

What is a canvas resize?

You can use the Resize Canvas tool to crop or to expand the size of your canvas to fit layered content or to add solid backgrounds.


1 Answers

Something like this should work, given you don't have security restrictions on the original canvas element:

var resizedCanvas = document.createElement("canvas");
var resizedContext = resizedCanvas.getContext("2d");

resizedCanvas.height = "100";
resizedCanvas.width = "200";

var canvas = document.getElementById("original-canvas");

resizedContext.drawImage(canvas, 0, 0, 200, 100);
var myResizedData = resizedCanvas.toDataURL();
like image 91
Nick Avatar answered Sep 30 '22 04:09

Nick