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 a
I didn't find any build-in events to detect new canvas dimensions, so I tried to find a workaround for two scenarios.
function onresize()
{
// handle canvas resize event here
}
var _savedWidth = canvas.clientWidth;
var _savedHeight = canvas.clientHeight;
function isResized()
{
if(_savedWidth != canvas.clientWidth || _savedHeight != canvas.clientHeight)
{
_savedWidth = canvas.clientWidth;
_savedHeight = canvas.clientHeight;
onresize();
}
}
window.addEventListener("resize", isResized);
(new MutationObserver(function(mutations)
{
if(mutations.length > 0) { isResized(); }
})).observe(canvas, { attributes : true, attributeFilter : ['style'] });
For detecting any JavaScript canvas.style changes, the MutationObserver API is good for. It doesn't detect a specific style property, but in this case it is sufficient to check if canvas.clientWidth and canvas.clientHeight has changed.
If the canvas size is declared in a style-tag with a percent unit, we have a problem to interpret the css selectors correctly (>, *, ::before, ...) by using JavaScript. I think in this case the best way is to set a window.resize handler and also check the canvas client size.