<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>ラフなブラシ描画 V2</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
font-family: Arial, sans-serif;
background-color: dimgray;
}
#canvas {
border: 1px solid #000;
margin-top: 0px;
background-color: white;
}
#controls {
margin-top: 10px;
}
h1 {
color: white;
font-size: 20px;
}
.white {
color: white;
}
#undoButton {
margin-left: 10px;
}
</style>
</head>
<body>
<h1>Rough Brush Painting V2</h1>
<canvas id="canvas"
width="800" height="600"></canvas>
<div id="controls">
<label for="colorPicker" class="white">color: </label>
<input type="color" id="colorPicker" value="black">
   
<label for="brushSize" class="white">size: </label>
<input type="range" id="brushSize"
min="1" max="50" value="5">
   
<button id="undoButton">Undo</button>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const colorPicker = document.getElementById('colorPicker');
const brushSize = document.getElementById('brushSize');
const undoButton = document.getElementById('undoButton');
let painting = false;
let brushColor = colorPicker.value;
let brushWidth = brushSize.value;
// Undo用にキャンバスの履歴を保存するスタック
const historyStack = [];
// 現在のキャンバスの状態を履歴に保存
function saveState() {
historyStack.push(canvas.toDataURL());
}
// historyStackから前の状態を取得し、
// その画像データを使用しキャンバスの状態を復元。
// new Image()とdrawImage()メソッドを使用。
function restoreState() {
if (historyStack.length > 0) {
const previousState = historyStack.pop();
const img = new Image();
img.src = previousState;
img.onload = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
};
}
}
// 開始位置
function startPosition(e) {
painting = true;
saveState();
draw(e);
}
// 終了位置
function finishedPosition() {
painting = false;
ctx.beginPath();
}
// 描画開始
function draw(e) {
if (!painting) return;
ctx.lineWidth = brushWidth;
ctx.lineCap = 'round';
ctx.strokeStyle = brushColor;
ctx.lineTo(e.clientX -
canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX -
canvas.offsetLeft, e.clientY - canvas.offsetTop);
}
canvas.addEventListener('mousedown', startPosition);
canvas.addEventListener('mouseup', finishedPosition);
canvas.addEventListener('mousemove', draw);
// ブラシカラー変更
colorPicker.addEventListener('input', (e) => {
brushColor = e.target.value;
});
// ブラシサイズ変更
brushSize.addEventListener('input', (e) => {
brushWidth = e.target.value;
});
// キャンバスの状態を1つ前に戻します。
undoButton.addEventListener('click', restoreState);
</script>
</body>
</html>
<!-- index.html -->