イナヅマTVログ

Canvas始めました – 拡大・縮小とかやってみる

| 0件のコメント

拡大・縮小するの巻。

setTransformでも行えるが、引数を簡略化した関数としてscale: 拡大・縮小が用意されている。

HTML

<canvas id='canvas'></canvas>

拡大(scale)
JavaScript

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillStyle = '#0000ff';
context.fillRect(10,10,50,50);
 
context.setTransform(1,0,0,1,0,0);
context.scale(2,2);
context.fillStyle = '#ff0000';
context.fillRect(10,10,50,50);
 
context.setTransform(3,0,0,3,0,0);
context.fillStyle = '#00ff00';
context.fillRect(10,10,50,50);
 
context.setTransform(1,0,0,1,0,0);

canvas scale +

scale
horizontal scale:float, vertical scale:float

scaleさせるとPosition(x座標, y座標)値も同様にscaleされるので注意が必要。
context.setTransform(2,0,0,2,0,0) と context.scale(2,2)は等価。

縮小(scale)
JavaScript

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillStyle = '#0000ff';
context.fillRect(10,10,150,150);
 
context.setTransform(1,0,0,1,0,0);
context.scale(0.5,0.5);
context.fillStyle = '#ff0000';
context.fillRect(10,10,150,150);
 
context.scale(0.5,0.5);
context.fillStyle = '#00ff00';
context.fillRect(10,10,150,150);
 
context.setTransform(1,0,0,1,0,0);

canvas scale -

setTransform(1,0,0,1,0,0)せずにscaleを続けると前回のscale値と掛け合わされるので注意。
まめにsetTransform(1,0,0,1,0,0)するが吉。

上記のコードをcontext.setTransform(1,0,0,1,0,0)を挟む形に書き換えると以下のようになる。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.fillStyle = '#0000ff';
context.fillRect(10,10,150,150);
 
context.setTransform(1,0,0,1,0,0);
context.scale(0.5,0.5);
context.fillStyle = '#ff0000';
context.fillRect(10,10,150,150);
 
context.setTransform(1,0,0,1,0,0);
context.scale(0.25,0.25);
context.fillStyle = '#00ff00';
context.fillRect(10,10,150,150);
 
context.setTransform(1,0,0,1,0,0);

以下の2つのコードは同じ結果になる。

context.setTransform(1,0,0,1,0,0);
context.scale(0.5,0.5);
context.scale(0.5,0.5);
context.setTransform(1,0,0,1,0,0);
context.scale(0.5,0.5);
 
context.setTransform(1,0,0,1,0,0);
context.scale(0.25,0.25);

コメントを残す

必須欄は * がついています


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください