层叠加,效果图如下
<!DOCTYPE html> <html> <head> <title>html5之Canvas学习</title> <script> function init(){ var canvas = document.getElementById("canvas"); var ctx = canvas.getContext('2d'); var rectWidth = 150; var rectHeight = 75; ctx.save(); // save state 1 ctx.translate(canvas.width / 2, canvas.height / 2); ctx.save(); // save state 2 ctx.rotate(Math.PI / 4); ctx.save();// save state 3 ctx.scale(2, 2); ctx.fillStyle ="blue"; ctx.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); ctx.restore(); // restore state 3 ctx.fillStyle ="red"; ctx.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); ctx.restore(); // restore state 2 ctx.fillStyle ="yellow"; ctx.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); ctx.restore(); // restore state 1 ctx.fillStyle ="green"; ctx.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight); } </script> </head> <body> <canvasheight="200"id="canvas"> element not supported. </canvas> </body> </html>
来自于