HTML5 canvas提供了允许直接修改转换矩阵的方法。转换矩阵最初必须是身份转换。然后可以使用转换方法对其进行调整。
让我们看一个画布转换的例子-
<!DOCTYPE HTML> <html> <head> <script> function drawShape(){ //使用DOM获取canvas元素 var canvas = document.getElementById('mycanvas'); //确保不支持画布时不执行 if (canvas.getContext){ //使用getContext使用画布进行绘制 var ctx = canvas.getContext('2d'); var sin = Math.sin(Math.PI/6); var cos = Math.cos(Math.PI/6); ctx.translate(200, 200); var c = 0; for (var i=0; i <= 12; i++) { c = Math.floor(255 / 12 * i); ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")"; ctx.fillRect(0, 0, 100, 100); ctx.transform(cos, sin, -sin, cos, 0, 0); } ctx.setTransform(-1, 0, 0, 1, 200, 200); ctx.fillStyle = "rgba(100, 100, 255, 0.5)"; ctx.fillRect(50, 50, 100, 100); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body onload = "drawShape();"> <canvas id = "mycanvas" width = "400" height = "400"></canvas> </body> </html>