1
1

More than 3 years have passed since last update.

【JavaScript】超簡単なお絵かきアプリを作りました

Last updated at Posted at 2020-12-13

完成物
demo

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);
});

スクリーンショット 2020-12-06 23.33.23.png

楽しい・・・
時間かけたらもっと本格的なものが作れそうです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1