Html5 Canvas transform setTransform

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   java   sp   

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 DOMvar canvas = document.getElementById(“mycanvas”);// Make sure we don”t execute when canvas isn”t supportedif (canvas.getContext){// use getContext to use the canvas for australian casinos online drawingvar 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>

 

Html5 Canvas transform setTransform

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.