移動するの巻。
setTransformでも行えるが、引数を簡略化した関数としてtranslateが用意されている。
translate(x, y)
HTML
<canvas id='canvas'></canvas> |
JavaScript
var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = '#0000ff'; context.fillRect(10,10,50,100); context.translate(50,0); context.fillStyle = '#ff0000'; context.fillRect(10,10,50,100); context.translate(50,0); context.fillStyle = '#00ff00'; context.fillRect(10,10,50,100); context.setTransform(1,0,0,1,0,0); |
上記のコードをsetTransformを使うと以下の様になる。
var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.fillStyle = '#0000ff'; context.fillRect(10,10,50,100); context.setTransform(1,0,0,1,50,0); //context.translate(50,0); context.fillStyle = '#ff0000'; context.fillRect(10,10,50,100); context.setTransform(1,0,0,1,100,0); //context.translate(50,0); context.fillStyle = '#00ff00'; context.fillRect(10,10,50,100); context.setTransform(1,0,0,1,0,0); |
translate
を使うとMatrixが変更されてるので初期化せずに続けて使う時はそれを考慮して使用する。
update 2012-04-28
setTransform(Matrix)を理解するには野中先生のActionScriptの解説が良くわかります。
「変換行列」って聞くと数学嫌いにはちょっと手が出せない感じになりますが、丁寧に詳しく解説されているのでお勧めです。
ActionScriptと言ってもCanvas APIと同じように動作・使用できるので苦手意識をお持ちの方は是非お読みください。
変換行列を数学的に捉える
Matrixクラス
2次元平面の座標を変換する行列 - Matrixクラス
MatrixTransformerクラスによりインスタンスを任意の座標で回す
数学的なベクトルと行列からMatrix/Matrix3Dクラスを理解する