다중 마우스 이벤트 조합 실습
이 단계에서는 여러 마우스 이벤트를 결합하여 다양한 이벤트가 함께 작동하여 풍부한 사용자 경험을 만드는 방법을 보여주는 대화형 드로잉 애플리케이션을 만들 것입니다. 사용자가 마우스를 클릭하고 드래그하여 그릴 수 있는 간단한 드로잉 캔버스를 구현할 것입니다.
~/project 디렉토리에 다음 코드를 사용하여 새 파일 mouse-drawing.html을 만듭니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Interactive Drawing Canvas</title>
<style>
#drawingCanvas {
border: 2px solid #000;
background-color: #f0f0f0;
cursor: crosshair;
}
#colorPicker {
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>Interactive Drawing Canvas</h1>
<div>
<label for="colorPicker">Choose Color:</label>
<input type="color" id="colorPicker" value="#000000" />
<button id="clearCanvas">Clear Canvas</button>
</div>
<canvas id="drawingCanvas" width="600" height="400"></canvas>
<p id="drawingStatus">
Start drawing by clicking and dragging on the canvas
</p>
<script>
const canvas = document.getElementById("drawingCanvas");
const ctx = canvas.getContext("2d");
const colorPicker = document.getElementById("colorPicker");
const clearButton = document.getElementById("clearCanvas");
const drawingStatus = document.getElementById("drawingStatus");
let isDrawing = false;
let lastX = 0;
let lastY = 0;
// Mouse down event - start drawing
canvas.addEventListener("mousedown", startDrawing);
// Mouse move event - draw while mouse is pressed
canvas.addEventListener("mousemove", draw);
// Mouse up and mouse out events - stop drawing
canvas.addEventListener("mouseup", stopDrawing);
canvas.addEventListener("mouseout", stopDrawing);
// Clear canvas button
clearButton.addEventListener("click", clearCanvas);
function startDrawing(e) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
drawingStatus.textContent = "Drawing in progress...";
}
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = colorPicker.value;
ctx.lineWidth = 2;
ctx.lineCap = "round";
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
function stopDrawing() {
isDrawing = false;
drawingStatus.textContent = "Drawing stopped. Start again!";
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawingStatus.textContent = "Canvas cleared. Start drawing!";
}
</script>
</body>
</html>
이 대화형 드로잉 애플리케이션의 주요 기능:
- 여러 마우스 이벤트 결합:
mousedown: 그리기 시작
mousemove: 마우스가 눌린 상태에서 계속 그리기
mouseup 및 mouseout: 그리기 중지
- 색상 선택기를 사용하여 그리기 색상 변경 가능
- 캔버스 지우기 버튼으로 그림 초기화
- 상태 메시지로 사용자 피드백 제공
예시 상호 작용:
- 캔버스에서 클릭하고 드래그하여 그립니다.
- 색상 선택기를 사용하여 색상을 변경합니다.
- "Clear Canvas"를 클릭하여 그리기 영역을 초기화합니다.