HTML Canvas Curve through point

Description

HTML Canvas Curve through point

View in separate window

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Curve Through Point</title>
  </head>//from ww w.j ava2 s .  c om
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Move mouse on canvas element.</aside>
    <script>
captureMouse = function (element) {
  var mouse = {x: 0, y: 0, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;
  
  element.addEventListener('mousemove', function (event) {
    var x, y;
    
    if (event.pageX || event.pageY) {
      x = event.pageX;
      y = event.pageY;
    } else {
      x = event.clientX + body_scrollLeft + element_scrollLeft;
      y = event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    mouse.x = x;
    mouse.y = y;
    mouse.event = event;
  }, false);
  
  return mouse;
};
    window.onload = function () {
      var canvas = document.getElementById('canvas'),
          context = canvas.getContext('2d'),
          mouse = captureMouse(canvas),
          x0 = 100,
          y0 = 200,
          x2 = 300,
          y2 = 200;
        
      canvas.addEventListener('mousemove', function () {
        context.clearRect(0, 0, canvas.width, canvas.height);

        var x1 = mouse.x * 2 - (x0 + x2) / 2,
            y1 = mouse.y * 2 - (y0 + y2) / 2;

        //curve through mouse
        context.beginPath();
        context.moveTo(x0, y0);
        context.quadraticCurveTo(x1, y1, x2, y2);
        context.stroke();
      }, false);
    };
    </script>
  </body>
</html>



PreviousNext

Related