line selection - Javascript Canvas

Javascript examples for Canvas:Line

Description

line selection

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.js"></script> 
      <style id="compiled-css" type="text/css">

#myCanvas {//w  w w.j a  v a  2s  .  c  om
   width: 200px;
   height: 200px;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var c = document.getElementById("myCanvas"),
    ctx = c.getContext("2d"),
    lines = [{
        x1: 25,
        y1: 85,
        x2: 50,
        y2: 15
    }, {
        x1: 80,
        y1: 10,
        x2: 150,
        y2: 105
    }];
c.width = 200;
c.height = 200;
function draw(cx, cy) {
    ctx.clearRect(0, 0, c.width, c.height);
    lines.forEach(function(line) {
        ctx.beginPath();
        ctx.moveTo(line.x1, line.y1);
        ctx.lineTo(line.x2, line.y2);
        if (lineCircleIntersects(line.x1, line.y1, line.x2, line.y2, cx, cy, 5))
            ctx.strokeStyle = "red";
        else
            ctx.strokeStyle = "black";
        ctx.stroke();
    });
    console.log(ctx.strokeStyle);
}
draw(0,0);
function lineCircleIntersects(x1, y1, x2, y2, cx, cy, cr) {
    var dx = x2 - x1,
        dy = y2 - y1,
        a = dx * dx + dy * dy,
        b = 2 * (dx * (x1 - cx) + dy * (y1 - cy)),
        c = cx * cx + cy * cy,
        bb4ac;
    c += x1 * x1 + y1 * y1;
    c -= 2 * (cx * x1 + cy * y1);
    c -= cr * cr;
    bb4ac = b * b - 4 * a * c;
    return bb4ac >= 0;  // true: collision, false: no collision
}
$("#myCanvas").on("mousemove", function(e){
    draw(e.offsetX, e.offsetY);
});
    });

      </script> 
   </head> 
   <body> 
      <canvas id="myCanvas"></canvas>  
   </body>
</html>

Related Tutorials