Is there a way to dynamically extend the html5 canvas without clearing what's drawn on it?
-
18-09-2019 - |
Question
see this
when the output reaches the bottom of the page, i'd like the canvas to automatically extend so that it can keep going. I tried setting the canvas.height property, but it clears the window. Is there any way to do this?
Solution
What I do:
create dummy canvas with same size as your canvas.
dummyCanvas.getContext('2d').drawImage(yourCanvas, 0, 0);
newCanvas = recreate(yourCanvas);
newCanvas.getContext('2d').drawImage(dummyCanvas);
Not very pretty, especially in your situation where it would require you recreating the canvas 50+ times per second... Interested in seeing other answers... It works for me because I just resize the canvas when the clientWidth/clientHeight changes [window.onresize]
OTHER TIPS
I know this is sort of old now, however:
You don't need to recreate the canvas as ItzWarty explaines. You can do this:
<html>...
<canvas id="canvas"></canvas>
<canvas id="buffer" style="display:none;"></canvas>
...
</html>
Then this would be your javascript:
var canvas = document.getElementById('canvas');
var buffer = document.getElementById('buffer');
window.onresize = function(event) {
var w = $(window).width(); //Using jQuery for easy multi browser support.
var h = $(window).height();
buffer.width = w;
buffer.height = h;
buffer.getContext('2d').drawImage(canvas, 0, 0);
canvas.width = w;
canvas.height = h;
canvas.getContext('2d').drawImage(buffer, 0, 0);
}
Here you only change the size of the canvases, and you copy over the image. I am not sure, but I believe the performance is a bit better, and it is in my opinion simpler and easier to understand.