
Canvas를 클릭하면 랜덤한 색상의 도형(원 또는 네모)이 그려집니다. 그리고 그려진 도형은 서서히 지워집니다.
<!DOCTYPE html>
<style>
#myCanvas {
border: 3px solid lightgray;
max-width: 100%;
box-sizing: border-box;
}
</style>
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
setInterval(mist, 200);
canvas.addEventListener("click", draw);
function mist() {
ctx.fillStyle = "rgb(255,255,255,0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const colors = ["red", "blue", "green", "orange", "gold"];
function draw(ev) {
if (ev.offsetX < 0 ||
ev.offsetX >= canvas.clientWidth ||
ev.offsetY < 0 ||
ev.offsetY >= canvas.clientHeight)
return;
var rate = canvas.width / canvas.clientWidth;
var x = ev.offsetX * rate;
var y = ev.offsetY * rate;
ctx.fillStyle = colors[randInt(0, colors.length - 1)];
[drawRect, drawCircle][randInt(0, 1)](
x, y, randInt(1000, 2500)
);
}
function drawRect(x, y, area) {
var len = area ** 0.5; // 한변의 길이
ctx.fillRect(x - (len / 2), y - (len / 2), len, len);
}
function drawCircle(x, y, area) {
var r = (area / Math.PI) ** 0.5
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fill();
}
function randInt(a, b) {
return Math.floor(Math.random() * (b - a + 1)) + a;
}
</script>