HTML5 Game - Curve attracted by mouse

Introduction

context.quadraticCurveTo(cpx, cpy, x, y) takes two points as arguments:

  • The first is a control point that affects the shape of the curve
  • the second is the ending point of the curve.

The shape is a standard algorithm known as a quadratic Bezier curve.

This function draws a curve from one point to another, curving toward-but never touching-the control point.

Demo

ResultView the demo in separate window

<!doctype html>  
    <html>  
     <head>  
      <meta charset="utf-8">  
      <title>Drawing Curves</title>  
      <style>canvas{border:1px solid red;}</style>  
     </head>  
     <body>  
      <canvas id="canvas" width="400" height="400"></canvas>  
      <script>  
      window.onload = function () {  
        let canvas = document.getElementById('canvas'),  
            context = canvas.getContext('2d'),  
            mouse = captureMouse(canvas),  
            x0 = 100,  //w  w w.j a  va2s  .  c om
            y0 = 200,  
            x2 = 300,  
            y2 = 200;  
      
        canvas.addEventListener('mousemove', function () {  
          context.clearRect(0, 0, canvas.width, canvas.height);  
      
          let x1 = mouse.x,  
              y1 = mouse.y;  
          //curve toward mouse  
          context.beginPath();  
          context.moveTo(x0, y0);  
          context.quadraticCurveTo(x1, y1, x2, y2);  
          context.stroke();  
        }, false);  
      }
function captureMouse(element) {
  let 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) {
    let 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;
}         
      </script>  
     </body>  
    </html>

Related Topic