HTM5 之 Canvas save 、restore 恢复画布状态的理解
save是用来保存canvas状态,这句话很关键,意思是指后续对canvas的操作:平移、放缩、旋转、错切、裁剪等可以恢复。
我之前一直没能理解,认为对画布的画线等操作也可以恢复,其实不是这样子的,只是平移、放缩、旋转、错切、裁剪等操作。
看w3c官网对此的说明:
w3c的说法是path和render context's bitmaps不支持状态的恢复。
看完整的示例代码:
<!doctype html> <html lang="en"> <head> <script src="http://modernizr.com/downloads/modernizr-latest.js"></script> <meta charset="UTF-8"> <title>quadraticCurveTo Example</title> <script type="text/javascript"> window.addEventListener('load', eventWindowLoaded, false); function eventWindowLoaded() { canvasApp(); } function canvasSupport () { return Modernizr.canvas; } function canvasApp(){ if (!canvasSupport()) { return; }else{ var theCanvas = document.getElementById("canvas"); var context = theCanvas.getContext("2d"); } function drawScreen() { //draw a big box on the screen context.fillStyle = "black"; context.fillRect(10, 10, 200, 200); //------------------------- context.save(); context.beginPath(); //clip the canvas to a 50×50 square starting at 0,0 context.rect(0, 0, 40, 40); context.clip(); //red circle context.beginPath(); context.strokeStyle = "red"; context.lineWidth = 5; context.arc(100, 100, 100, (Math.PI/180)*0, (Math.PI/180)*360, false); //full circle context.stroke(); context.closePath(); context.restore(); //------------------------- //reclip to the entire canvas context.beginPath(); context.rect(0, 0, 110, 110); context.clip(); //draw a blue line that is not clipped context.beginPath(); context.strokeStyle = "blue"; context.lineWidth = 5; context.arc(100, 100, 50, (Math.PI/180)*0, (Math.PI/180)*360, false); //full circle context.stroke(); context.closePath(); } drawScreen(); } </script> </head> <body> <div style="position: absolute; top: 50px; left: 50px;"> <canvas id="canvas" width="500" height="500"> Your browser does not support HTML5 Canvas. </canvas> </div> </body> </html>
//-------------------------
这两个注释之间用到了一个画面裁剪:
//指定裁剪区域(clipping region)
context.rect(0, 0, 40, 40); //裁剪
context.clip();
在这个裁剪操作之前已经有了context.save() 操作
如果不save,restore操作,后续画的蓝色的圆是不会出来。因为已经被裁减了。(裁剪不分先后顺序)
//-------------------------
进行save,restore操作:
不进行save、restore操作
不知道大家理解了没,反正我已经理解了,多动手才能更好地做比较。