Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to zoom and pan an HTML5 Canvas by transforming the context using translate() and scale(), clearing the canvas, and then redrawing. Note that I am explicitly not calling save() and restore() around my transformations.

If I perform the standard ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height) then the entire visible canvas will not be cleared; downscaling or panning may cause this initial rectangle to not exactly cover the drawing area.

If I perform the Webkit-friendly clearing method...

var w=canvas.width;
canvas.width = 0;
canvas.width = w;

...then the cumulative transformation of the context is reset.

How can I best clear the entire canvas context without losing my transformation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

Keeping track of all the transformation information like you are presumably doing is what several others so far have done (like cake.js and my own library, for two). I think doing this will pretty much be an inevitability for any large canvas library.

Ilmari of cake.js even complained to mozilla: https://bugzilla.mozilla.org/show_bug.cgi?id=408804

You could instead call save/restore around your clear method:

// I have lots of transforms right now
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
// Will always clear the right space
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
ctx.restore();
// Still have my old transforms

Won't that satisfy your case?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...