<html>
<head>
</head>
<body>
<div id="main">
<div id="content">
<!-- サイズを指定しない場合、デフォルトのCanvasは横300、縦150っぽい -->
<canvas id="canvasid" width="550" height="550"></canvas>
</div>
</div>
<!-- HTML描画完了後に読み込んでほしいのでBodyの最後に記載 -->
<script src="./test.js"></script>
</body>
</html>
test.js
function draw() {
console.log("draw");
/* canvas要素のノードオブジェクト */
var canvas = document.getElementById('canvasid');
/* canvas要素の存在チェックとCanvas未対応[[ブラウザ]]の対処 */
if ( ! canvas || ! canvas.getContext ) {
return false;
}
/* 2Dコンテキスト */
var ctx = canvas.getContext('2d');
for (i = 0; i < 5; i++) {
/* 四角を描く */
ctx.beginPath();
ctx.moveTo(20 + i*100, 20 + i*100);
ctx.lineTo(120 + i*100, 20 + i*100);
ctx.lineTo(120 + i*100, 120 + i*100);
ctx.lineTo(20 + i*100, 120 + i*100);
ctx.closePath();
ctx.strokeStyle = 'rgb(' + i*50 + ',' + i*50 +',' + i*50+ ')'
ctx.fillStyle = 'rgb(' + i*40 + ',' + i*40 +',' + i*40 + ')'
ctx.stroke();//strokeStyleで指定された色で線が表示
ctx.fill();//fillStyleで指定された色で線を繋いだ四角形が表示
}
// 円描画
ctx.beginPath();
ctx.fillStyle = 'rgb(0, 155, 155)'
//arc関数 =円を描画(X座標の中心, Y座標の中心, 半径, 開始角度, 終了角度, 時計周り/反時計周り)
ctx.arc(100, 45, 35, 0, Math.PI*2, false);
ctx.fill();
// 四角描画
ctx.beginPath();
ctx.fillStyle = 'rgb(0, 155, 155)'
//rect関数 =四角形を描画(X座標の始点, Y座標の始点, 幅, 高さ)
ctx.rect(200, 20, 100, 30);
ctx.fill();
}
draw();
最終更新:2015年02月20日 10:26