LoginSignup
6
6

More than 5 years have passed since last update.

Canvasの基礎

Last updated at Posted at 2014-06-01

Canvasの描画

canvasを取得

//書き方
//canvas要素 = document.getElementById('エレメントID');
var canvasElement = document.getElementById('myCanvas');

2Dコンテクスト取得

//書き方
//2Dコンテクスト = canvas要素.getContext('2d');
var context2D = canvasElement.getContext('2d');

2Dコンテクストを描画

//書き方
//2Dコンテクスト.fillRect(x座標, y座標, 幅, 高さ);
context2D.fillRect(10, 10, 100, 100);

色を塗る

//書き方
//2Dコンテクスト.fillStyle = カラー値;
context2D.fillStyle = 'rgb(155, 187, 89)';

直線で形を描く

メソッド 内容
beginPath() パスのはじめ
closePath() パスを閉じる
fill() 塗り
storoke()
strokeStyle 線の塗り
lineWidth 太さ
moveTo() 直線の書き始めの座標
lineTo() 直線を結ぶ
context2D.beginPath();
context2D.moveTo(10,  10);
context2D.lineTo(110, 10);
context2D.lineTo(110,110);
context2D.lineTo(10,110);
context2D.closePath();
context2D.fill();
context2D.stroke();

星を描く

drawStar(2Dコンテクスト, 中心のx座標, 中心のy座標, 頂点数, 山の半径, 谷の半径)

山と谷の間の中心角の出し方

360/(頂点数-2) = 180 / 頂点数

山と谷のxy座標の出し方

x座標 = 半径 × cos角度 + 中心のx座標
y座標 = 半径 × sin角度 + 中心のy座標

サンプル

サンプル

参考サイト

Canvasリファレンス - HTML5.JP
canvas - jsdo.it

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6