Graphics - Dragging objects

<div>
    <canvas id="id-image-canvas" width="400" height="400" style="background-color: black"></canvas>
</div>

<script>
    function drawLine(ctx, angle) {
        angle = angle / 180 * Math.PI;
        var O = { x: 250, y: 300 };
        var R = 150;
        var P = { x: O.x + Math.cos(angle) * R, y: O.y + Math.sin(angle) * R };

        ctx.beginPath();
        ctx.moveTo(O.x, O.y);
        ctx.lineTo(P.x, P.y);
        ctx.closePath();
        ctx.strokeStyle = 'green';
        ctx.stroke();
    }

    function setPixel(imageData, x, y, r, g, b, a) {
        index = (x + y * imageData.width) * 4;
        imageData.data[index + 0] = r;
        imageData.data[index + 1] = g;
        imageData.data[index + 2] = b;
        imageData.data[index + 3] = a;
    }

    var line = { x1: 100, y1: 100, x2: 200, y2: 200, selected: false };
    var canvas = $('#id-image-canvas').get(0);
    var ctx = canvas.getContext('2d');

    function showDot(ctx, x, y) {
        const w = 5;
        ctx.fillStyle = 'red'
        ctx.fillRect(x - w / 2, y - w / 2, w, w);
    }

    function paintLine(lineObject) {
        ctx.beginPath()
        ctx.strokeStyle = 'yellow'
        ctx.moveTo(lineObject.x1, lineObject.y1)
        ctx.lineTo(lineObject.x2, lineObject.y2)
        if (lineObject.selected) {
            showDot(ctx, lineObject.x1, lineObject.y1);
            showDot(ctx, lineObject.x2, lineObject.y2);
        }
        ctx.closePath()
        ctx.stroke()
    }

    function isPointCloseToStroke(ctx, x, y) {
        const N = 3;
        for (var i = -N; i <= N; i++) {
            for (var j = -N; j <= N; j++) {
                if (ctx.isPointInStroke(x + i, y + j))
                    return true;
            }
        }
        return false;
    }

    function paint() {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        paintLine(line)
    }

    canvas.onmousedown = function (e) {
        start_point = { x: event.offsetX, y: event.offsetY };
        if (isPointCloseToStroke(ctx, point.x, point.y)) {
            line.selected = true;
        }
        else {
            line.selected = false;
        }
        paint();
    }

    canvas.onmousemove = function (e) {
        point = { x: event.offsetX, y: event.offsetY };
        if (line.selected && e.buttons === 1) {
            var dx = point.x - start_point.x;
            var dy = point.y - start_point.y;
            start_point = point;
            line.x1 += dx;
            line.x2 += dx;
            line.y1 += dy;
            line.y2 += dy;
            paint();
        }
    }

    paint()
</script>
  • Live Demo