Html5 Canvas transform setTransform

Html5 Canvas transform就是矩阵变换,一种坐标的变形。

坐标变形的三种方式,平移translate, 缩放scale以及旋转rotate都可以通过transform做到。

transform(m11, m12, m21, m22, dx, dy):这个方法必须将当前的变形矩阵乘上下面的矩阵:

m11

m21

dx

m12

m22

dy

0

0

1

也就是说假设 变化前A(x,y)得到 变换后B(x’,y’)可以通过乘以上述矩阵即可得到:

比如说:缩放scale

x”=x*a;            //x放大a倍

y”=y*b;            //y放大b倍

只需transform(a, 0, 0, b, 0, 0);

A(x,y)通过transform就得到了放大后的B(x’,y’);与方法context.scale(a,b)同效;

 

比如 旋转rotate

假设将(x,y)绕原点逆时针旋转θ得到(x”,y”),则:

x’=x*cosθ-y*sinθ

y’=x*sinθ y*cosθ

只需transform(Math.cos(θ*Math.PI/180),Math.sin(θ*Math.PI/180),-Math.sin(θ*Math.PI/180),Math.cos(θ*Math.PI/180),0,0)

A(x,y)通过transform就得到了旋转后的B(x’,y’);与方法context.rotate(θ)同效;

就是说只要知道变化前和变换后的坐标转化公式,就能通过与矩阵相乘的方法得到;

setTransform这个方法重置当前的变形矩阵为单位矩阵,然后以相同的参数调用 transform 方法。就是消除前面transform行为对这次行为的影响;

提供一个代码可以自己研究一下

<!DOCTYPE HTML>
<html>
<head>
<script type=”text/javascript”>
function drawShape(){
// get the canvas element using the DOM
var canvas = document.getElementById(“mycanvas”);
// Make sure we don”t execute when canvas isn”t supported
if (canvas.getContext){
// use getContext to use the canvas for australian casinos online drawing
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 ratedbet.co.uk 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>

 

posted @ 2014-11-09 16:20  bigwhiteshark(云飞扬)  阅读(2473)  评论(0编辑  收藏  举报