JS:キャンバスによる描画サンプル

JavaScript

キャンバスによる描画

canvas1.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>canvasによる描画</title>
	<style>
		canvas{ background-color: skyblue;}
	</style>
	<script>
		let canvas = null;
		let g = null;

		function draw(){
			// キャンバスの初期設定
			canvas = document.getElementById("canvas");
			g = canvas.getContext("2d");
			// 画面をクリア
			g.clearRect(0, 0, canvas.width, canvas.height);
			// □を描画
			g.strokeStyle = "#000";	// 枠線の色
			g.strokeWidth = "5px";	// 枠線の太さ
			g.strokeRect(50, 100, 400, 300);			// この時点で描画される
			// □の中を塗りつぶす
			g.fillStyle = "white";
			g.fillRect(50, 100, 400, 300);
			// ●を描画
			g.beginPath();
			g.fillStyle = "red";	// 塗りつぶす色
			g.arc(250, 250, 80, 0, Math.PI*2, false);
			g.fill();									// この時点で描画される
		}

		window.addEventListener("load", draw);
	</script>
</head>
<body>
	<h1>canvasによる描画</h1>
	<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>

キャンバスによるアニメーション

canvas_anim.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>canvasでアニメーション</title>
	<script>
		let canvas = null;
		let g = null;
		let x, y;
		let r;

		function drawAnim(){
			// キャンバスの初期設定
			canvas = document.getElementById("canvas");
			g = canvas.getContext("2d");
			// 画面をクリア
			g.fillStyle = "gray";
			g.fillRect(0, 0, canvas.width, canvas.height);
			// ●を描画
			g.beginPath();
			g.fillStyle = "orange";	// 塗りつぶす色
			g.arc(x, y, r, 0, Math.PI*2, false);
			g.fill();
			// アニメーションする
			y+=3;
			x+=3;
			// 上に戻る
			if(y > 550){
				y = -50;
				r += 10;
			}
			if(x > 550) x = -50;
			setTimeout(drawAnim, 30);
		}

		window.addEventListener("load", function(){
			y = 0;
			x = 0;
			r = 50;
			drawAnim();
		});
	</script>
</head>
<body>
	<h1>canvasでアニメーション</h1>
	<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>

コメント