Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically resize canvas window with javascript/jquery?

Tags:

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/

like image 674
Max Hudson Avatar asked Jul 06 '12 19:07

Max Hudson


People also ask

How do I resize a canvas to resize a window?

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 .

How can an html5 canvas size be changed so that it fits the entire window?

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.

How do you resize a 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.


2 Answers

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)     }); })(); 

like image 75
Josiah Ruddell Avatar answered Nov 15 '22 05:11

Josiah Ruddell


 (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) 
like image 20
Knights Avatar answered Nov 15 '22 05:11

Knights