LoginSignup
6
6

More than 5 years have passed since last update.

[HTMLでお絵描き入門]JavaScriptでCanvas上に直線を描く

Last updated at Posted at 2018-07-04

canvas,JavaScriptのマウスイベントで直線を描きます。
canvasで線分を描く方法のままマウスイベントを設定すると問題が発生するため、
問題点・解決案を書きました。

ゴール

下イメージを目指します。
ゴール.gif

問題点

マウスイベント
1.onmousedown->始点を設定
2.onmousemove->始点~カーソル位置までを線で結ぶ
3.onmouseup ->終点を設定/始点~終点までを線で結ぶ
を設定するだけだとマウスが動いた軌跡全てに線が引かれてしまいます。
これはcanvasが動画のように描画していることに起因しています。
canvas_sequence.gif

解決策

カーソル位置の座標管理+描画面を都度消去する処理を追加
※詳細は一番下デモ画面を参照して下さい。コードも記載しています。
1.終点座標を配列管理するための[]を用意

let storedLines = [];

2.描画を消す+始点~終点を線分で結ぶ関数を設定。

function Redraw(){
    ctx.clearRect(0,0,can.width,can.height);
    if(storedLines.length == 0){
        return;
    }
    for(let i = 0; i<storedLines.length; i++){
        ctx.beginPath();
        ctx.moveTo(storedLines[i].x1, storedLines[i].y1);
        ctx.lineTo(storedLines[i].x2, storedLines[i].y2);
        ctx.stroke();
    }
}

3.onmousemove->2で設定した関数を使います。
4.onmouseup ->終点座標をstoredLinesへpush

デモ

See the Pen HTML/Canvas Drawing Stroke Line by Keita Minowa (@keita-minowa) on CodePen.

canvasで線分が描けました。

参考URL

https://stackoverflow.com/questions/22441446/mouse-interaction-in-html5-canvas-drawing-lines

6
6
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
6
6