index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="black"></div>
<div id="red"></div>
<div id="green"></div>
<script src="./main.js"></script>
</body>
</html>
style.css
.dot {
position: absolute;
width: 10px;
height: 10px;
}
#black {
width: 100px;
height: 100px;
background-color: black;
}
#red {
width: 100px;
height: 100px;
background-color: red;
}
#green {
width: 100px;
height: 100px;
background-color: green;
}
main.js
let clicking;
let color = 'black';
const black = document.getElementById('black');
const red = document.getElementById('red');
const green = document.getElementById('green');
black.addEventListener('click', () => {
color = 'black';
});
red.addEventListener('click', () => {
color = 'red';
});
green.addEventListener('click', () => {
color = 'green';
});
document.addEventListener('mousedown', () => {
clicking = true;
});
document.addEventListener('mouseup', () => {
clicking = false;
});
document.addEventListener('mousemove', (e) => {
if (!clicking) {
return;
}
const dot = document.createElement('div');
dot.className = 'dot';
dot.style.left = `${e.clientX}px`;
dot.style.top = `${e.clientY}px`;
dot.style.backgroundColor = color;
document.body.append(dot);
});
楽しい・・・
時間かけたらもっと本格的なものが作れそうです。