Lines with mouse (canvas)

by muztv

HTML

<canvas id="canvas" height="500" width="500"></canvas>
<div id="status"></div>

CSS

canvas {
    cursor: default;
    border: 1px black solid;
}

JavaScript

var beforeX;
var beforeY;
var afterX;
var afterY;


var x1 = 10
var y1 = 10
var x2 = 100
var y2 = 10
var x3 = 100
var y3 = 200


function initCanvas() {
    var ctx = document.getElementById('canvas').getContext('2d');
     function d() {
       ctx.beginPath();
       ctx.strokeStyle = '#ff0000';
       ctx.moveTo(x1, y1);
       ctx.lineTo(x2, y2);
       ctx.quadraticCurveTo(x2, y3, x3, y3);
       ctx.stroke();
     }
     
     d()
        
    ctx.canvas.addEventListener('mousemove', function (event) {
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        var status = document.getElementById('status');
        var x = mouseX - x1
        var y = mouseY - y1
        //var isLine = (x > 0 && y > 0) 
        //		&& Math.abs(a - x / y) < 0.5 * (x / y)
        //    && x < (x2 - x1)
        //    && y < (y2 - y1);
            
        //console.log(a, x / y)
        
        var isOnLine = getLineFn(x1, y1, x2, y2);
				var isLine = isOnLine(mouseX, mouseY);
        
        if (isLine) {
        	 ctx.beginPath();
           ctx.strokeStyle = '#0000ff';
           ctx.moveTo(x1, y1);
           ctx.lineTo(mouseX, mouseY)
           ctx.stroke();
           alert('11')
           //d()
        }
        status.innerHTML = mouseX + " | " + mouseY + " | " + isLine;
    });
    ctx.canvas.addEventListener('mousedown', function (event) {
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        beforeX = mouseX;
        beforeY = mouseY;
        //ctx.fillRect(mouseX - 15, mouseY - 15, 30, 30);
    });
}
setInterval(initCanvas, 100);