How can I resize a canvas with javascript/jquery?
Resizing using the css function and applying it to the canvas element just stretches the content as if you were stretching an image.
How would I go about doing this without the stretching?
http://jsfiddle.net/re8KU/4/
Resizing the canvas on the fly is quite easy. To do it, simply set the width and height properties of the Canvas object, and then redraw the canvas contents: Canvas . width = 600 ; Canvas .
Set the Size with CSS We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%. And we can draw on it with: const canvas = document.
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.
Make a function that does the drawing, then re-draw whenever something changes that requires it (like a page resize, etc). Try it out
Make sure you set the context.canvas.width/height, not CSS width/height. Also note that setting the size clears the canvas.
How I would write it:
(function(){ var c = $("#canvas"), ctx = c[0].getContext('2d'); var draw = function(){ ctx.fillStyle = "#000"; ctx.fillRect(10,10,50,50); }; $(function(){ // set width and height ctx.canvas.height = 600; ctx.canvas.width = 600; // draw draw(); // wait 2 seconds, repeate same process setTimeout(function(){ ctx.canvas.height = 400; ctx.canvas.width = 400; draw(); }, 2000) }); })();
(function($) { $.fn.extend({ //Let the user resize the canvas to the size he/she wants resizeCanvas: function(w, h) { var c = $(this)[0] c.width = w; c.height = h } }) })(jQuery)
Use this little function I created to take care of resizing on the go. Use it this way --
$("the canvas element id/class").resizeCanvas(desired width, desired height)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With