HTML5 canvasを使った矩形選択と選択範囲塗りつぶし

  • 16
    いいね
  • 3
    コメント

概要

  • お絵かきアプリでよくある矩形選択→選択範囲塗りつぶしをcanvasとjavascriptを使って再現してみた。
  • 備忘録として載っけておく。
  • 業務で使うかも。

動作

rectangleSelect.gif

ソース

app.js
var app = (function (){
    //キャンバスエレメント
    var _displayLayer;
    var _drowingLayer;
    //描画コンテキスト
    var _ctxDisplayLayer;
    var _ctxDrowingLayer;

    // キャンバスサイズ
    var _canvasY;
    var _canvasX;

    // コンストラクタ
    var app = function (_display, _drowing) {
        _displayLayer    = _display;
        _drowingLayer    = _drowing;
        _canvasY         = _drowingLayer.clientHeight;
        _canvasX         = _drowingLayer.clientWidth;
        _ctxDisplayLayer = _display.getContext("2d");
        _ctxDrowingLayer = _drowing.getContext("2d");
        _drowingLayer.addEventListener("mousedown", onMouseDown, false);
        _drowingLayer.addEventListener("mouseup"  , onMouseUp  , false);
    };

    // 矩形オブジェクト
    var _rectangle = {
        startY:0,
        startX:0,
        endY:0,
        endX:0,
        clear:function () {
            this.startY = 0;
            this.startX = 0;
            this.endY   = 0;
            this.endX   = 0;
        }
    };
    function onMouseDown (e) {
        _rectangle.startY = e.clientY;
        _rectangle.startX = e.clientX;
        _drowingLayer.addEventListener ("mousemove", onMouseMove, false);
    };

    function onMouseMove (e) {
        _ctxDrowingLayer.clearRect(0, 0, _canvasX, _canvasY);
        _rectangle.endY = e.layerY - _rectangle.startY;
        _rectangle.endX = e.layerX - _rectangle.startX;
        _ctxDrowingLayer.strokeRect (_rectangle.startX, _rectangle.startY, _rectangle.endX, _rectangle.endY);
    };

    function onMouseUp (e) {
        _ctxDisplayLayer.fillRect(_rectangle.startX, _rectangle.startY, _rectangle.endX, _rectangle.endY);
        _rectangle.clear();
        _ctxDrowingLayer.clearRect(0, 0, _canvasX, _canvasY);
        _drowingLayer.removeEventListener ("mousemove", onMouseMove, false);
    };

    return app;
})();
ImageEditTest.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>canvasを用いた画像編集アプリ</title>
    <link rel="stylesheet" type="text/css" href="main.css">
    <script type="text/javascript" src="app.js"></script>
</head>
<body>
    <div class="main">
        <canvas id="display" class="display" width="1280" height="720"></canvas>
        <canvas id="drowing" class="drowing" width="1280" height="720"></canvas>
    </div>
    <script type="text/javascript">
        var display  = document.getElementById("display");
        var drowing  = document.getElementById("drowing");
        var instance = new app(display, drowing);
    </script>
</body>
</html>
main.css
.display{
    border: solid 1px;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 0;
}

.drowing{
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
}