木曜日, 9月 10, 2026

Let's start JavaScript 110 
ランダムに円、三角、四角を表示

ランダムに円、三角形、四角形を表示するだけです。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ランダム図形表示</title>
<style>
body{
background: black;
color: white;
margin: 20px;
}
canvas{
border:2px solid white;
}
</style>
</head>
<body>
<center>
<h3>ランダム図形表示</h3>

<canvas id="canvas" width="800" height="600"></canvas>
<br>
<button onclick="drawShapes()">&emsp;リドロー&emsp;</button>

<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

function rand(min, max){
return Math.random() * (max - min) + min;
}

function color(){
return `hsl(${Math.random()*360},80%,60%)`;
}

function drawShapes(){

ctx.clearRect(0,0,canvas.width,canvas.height);

for(let i=0;i<50;i++){

const type = Math.floor(Math.random()*3);

const size = rand(10,100);
const x = rand(size/2, canvas.width-size/2);
const y = rand(size/2, canvas.height-size/2);

ctx.fillStyle = color();

switch(type){

case 0: // 円
ctx.beginPath();
ctx.arc(x,y,size/2,0,Math.PI*2);
ctx.fill();
break;

case 1: // 四角
ctx.fillRect(
x-size/2,
y-size/2,
size,
size
);
break;

case 2: // 三角
ctx.beginPath();
ctx.moveTo(x,y-size/2);
ctx.lineTo(x-size/2,y+size/2);
ctx.lineTo(x+size/2,y+size/2);
ctx.closePath();
ctx.fill();
break;
}
}
}

// 初回表示
drawShapes();
</script>
</center>
</body>
</html>

実行直後の画面です。既にランダムです。

[リドロー]で再表示。

ランダムなので同じイメージは二度と出てきません。