Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event for canvas resize

Tags:

It appears that altering the dimensions of a canvas clears any drawing already done on that canvas.

Is there an event that fires on canvas resize, so I can hook it and redraw when it occurs?

like image 840
rampion Avatar asked Apr 28 '11 21:04

rampion


People also ask

How do you dynamically resize canvas?

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 .

What is resize method in JavaScript?

Definition and Usage. The onresize event occurs when the browser window has been resized. Tip: To get the size of an element, use the clientWidth, clientHeight, innerWidth, innerHeight, outerWidth, outerHeight, offsetWidth and/or offsetHeight properties.

How do I capture a Windows resize event?

Answer: Use the addEventListener() Method You can simply use the addEventListener() method to register an event handler to listen for the browser window resize event, such as window. addEventListener('resize', ...) . The following example will display the current width and height of the browser window on resize.

How do you scale a canvas?

You can scale your canvas with content by "bouncing" the content off a temporary canvas while you resize the original canvas. This save+redraw process is necessary because canvas content is automatically cleared when you resize the canvas width or height.


1 Answers

David Mulder's answer is an improvement, but it looks like it will trigger after waiting timeout milliseconds after the first resize event. In other words, if more resizes happen before the timeout, it doesn't reset the timer. I was looking for the opposite; I wanted something which would wait a little bit of time to let the resize events stop, and then fire after a certain amount of time after the last one. The following code does that.

The ID of any currently-running timer will be in timer_id. So, whenever there's a resize, it checks to see if there's already a time running. If so, it cancels that one and starts a new one.

function setResizeHandler(callback, timeout) {     var timer_id = undefined;     window.addEventListener("resize", function() {         if(timer_id != undefined) {             clearTimeout(timer_id);             timer_id = undefined;         }         timer_id = setTimeout(function() {             timer_id = undefined;             callback();         }, timeout);     }); }  function callback() {     // Here's where you fire-after-resize code goes.     alert("Got called!"); } setResizeHandler(callback, 1500); 
like image 200
Jemenake Avatar answered Sep 28 '22 02:09

Jemenake