<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
class Circle {
constructor(x, y, radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
}
}
let circles = [new Circle(250, 250, 50)];
circles[0].draw();
canvas.addEventListener('click', (event) => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
for (let i = circles.length - 1; i >= 0; i--) {
const circle = circles[i];
const distance = Math.sqrt(Math.pow(x - circle.x, 2) + Math.pow(y - circle.y, 2));
if (distance <= circle.radius) {
circles.splice(i, 1);
circles.push(new Circle(circle.x - circle.radius / 2, circle.y, circle.radius / 2));
circles.push(new Circle(circle.x + circle.radius / 2, circle.y, circle.radius / 2));
break;
}
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
circles.forEach(circle => circle.draw());
});
</script>
</body>
</html>
'PROGRAMMING > JavaScript' 카테고리의 다른 글
javascript == 연산자, === 연산자 (0) | 2014.12.12 |
---|---|
Data-Driven Documents - d3js.org (0) | 2014.08.01 |
[jquery] 예제 - 부모 엘리먼트의 class 변경 (0) | 2010.08.23 |
마지막에 수정된 날짜. (0) | 2010.07.12 |
javascript fadein fadeout (0) | 2010.07.11 |