LoginSignup
2
3

More than 5 years have passed since last update.

ライブコーディングでお絵かきアプリつくった

Posted at

概要

ライブコーディングすることになったので、お絵かきアプリをつくった。
かなり用意していったので「ライブ」かどうかは怪しいが、5分ほどで動くものができるので余興とかで使えるかも。

仕様

  • canvasでお絵かきができる
  • 使用できるのは(ペイントで言う)ペンのみ
  • ペンの色が変えられる(赤、青、緑、黄、黒)
  • 保存は出来ない
  • クライアントサイドで完結

コード

index.html
<!DOCTYPE html>
<html>
  <head>
    <title>お絵かきアプリ</title>
    <style>
      body {
        background: #666;
      }
      canvas {
        background: #fff;
      }
      button {
          width: 50px;
      }
    </style>
  </head>
  <body>
    <div>
      <canvas id="canvas" width="640" height="480"></canvas>
    </div>
    <div>
      <button onclick="changeColor('red')">red</button>
      <button onclick="changeColor('blue')">blue</button>
      <button onclick="changeColor('green')">green</button>
      <button onclick="changeColor('yellow')">yellow</button>
      <button onclick="changeColor('black')">black</button>
    </div>
    <script src="app.js"></script>
  </body>
</html>
app.js
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');

document.addEventListener('mousedown', (event) => {
    context.beginPath();
    context.moveTo(event.clientX, event.clientY);
    document.addEventListener('mousemove', stroke);
});

function stroke(event) {
    context.lineTo(event.clientX, event.clientY);
    context.stroke();
}

document.addEventListener('mouseup', (event) => {
    document.removeEventListener('mousemove', stroke);
});

function changeColor(color) {
    context.strokeStyle = color;
}

所感など

JavaScriptが慣れてないこともあり、最初は練習が結構必要だった。
結構面白かったので定期的にアウトプットをするという目的でやってみると良いかも。

その他

canvasのwidthとheightをstyleタグの中で指定したらうまくいかなかった。(原因は特に調べてない)
※ canvas自信ニキいたら教えてください

2
3
1

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
2
3