図形表示
円を描く
canvas の上に図形を表示します。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<link rel="stylesheet" href="style.css">
<script src="main.js"></script>
</head>
<body>
<h1>canvas に図形を描く</h1>
<canvas id="mainCanvas" width="480px" height="480"></canvas>
</body>
</html>
スタイルシートのファイルとJavaScriptファイルを読み込みます。
スタイルシートのファイル
<link rel="stylesheet" href="main.css">
JavaScriptファイルを読み込みます
<script src="main.js"></script>
canvas を用意する。
<canvas id="mainCanvas"></canvas>
style.css
body {
margin: 0px;
background-color: lightgray;
}
#mainCanvas {
border: solid 1px black;
}
canvas の表示範囲を指定。
境界線を表示
main.js
window.onload = function() {
cycle(50, 100, 30, "red"); // 赤い円を描く 関数呼び出し
}
// 赤い円を描く
function cycle (x, y, p, colo) {
let c = document.getElementById("mainCanvas").getContext("2d"); //描画コンテキスト取得
c.beginPath(); // パスの初期化
c.arc(x, y, p, 0, Math.PI*2, true); // x, y, 半径, 開始角 ラジアン, 終了角 ラジアン, 反時計回り
c.fillStyle= colo; // 塗りつぶしの色指定
c.fill(); // 塗りつぶし
c.stroke(); // 描画
}
main.js を編集してみよう
円と四角を交互に描くプログラム
main.js
window.onload = function() {
let cv = document.getElementById("mainCanvas").getContext("2d"); //描画コンテキスト取得
let i=0;
for (let y = 25; y < 480-15; y += 50) {
for (let x = 25; x < 480-15; x += 50) {
i++;
if (i % 2 == 1) { // 余りを求める
cycle(cv, x, y, 15, "red"); // 赤い円を描く 関数呼び出し
} else {
rect(cv, x-15, y-15, 30, 30, "blue"); // 青い四角を描く 関数呼び出し
}
}
}
}
// 円を描く
function cycle (cv, x, y, p, colo) {
cv.beginPath(); // パスの初期化
cv.arc(x, y, p, 0, Math.PI*2, true); // x, y, 半径, 開始角 ラジアン, 終了角 ラジアン, 反時計回り
cv.fillStyle= colo; // 塗りつぶしの色指定
cv.fill(); // 塗りつぶし
cv.stroke(); // 線描画
}
// 四角形を描く
function rect (cv, x, y, w, h, colo) {
cv.fillStyle= colo; // 塗りつぶしの色指定
cv.fillRect(x, y, w, h); // x, y, 幅, 高さ
}