Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - Clear entire, transformed HTML5 Canvas while preserving context transform

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

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

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...