複数のマウスイベントを組み合わせる練習
このステップでは、複数のマウスイベントを組み合わせたインタラクティブな描画アプリケーションを作成します。これにより、異なるイベントがどのように協働して豊かなユーザー体験を作成するかを示します。クリックとドラッグで描画できる簡単な描画キャンバスを実装します。
~/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" をクリックして描画領域をリセットする