Canvas Radial Gradient动画

时间:2017-06-21 10:43:45

标签: javascript html canvas

我的脚本需要一些帮助。我试图让“亮点”随着我的canvas上的鼠标移动,但看起来它的移动方式比游标更快。问题在哪里?

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
    position:absolute;
        margin: 0px;
        padding: 0px;
      }
      canvas{
    position: fixed;
    height:900px;
    Width:900px;
    }

    </style>
  </head>
  <body>
    <canvas id="myCanvas"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      window.onmousemove=function(){
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.rect(0, 0, canvas.width, canvas.height);

      // create radial gradient
      var grd = context.createRadialGradient(event.clientX, event.clientY, 5, event.clientX+20, event.clientY+20, 100);
      // light blue
      grd.addColorStop(0, '#ffffff');
      // dark blue
      grd.addColorStop(0.5, '#000000');

      context.fillStyle = grd;
      context.fill();
      };

    window.onclick= function(){
        alert("X: " + event.clientX + " " +"Y: " + event.clientY)
    }
    </script>
  </body>
</html>  

1 个答案:

答案 0 :(得分:2)

保持鼠标事件和渲染分离,因为鼠标事件未同步到显示器。鼠标事件只记录鼠标状态(每秒最多100个以上样本。)动画帧仅在能够显示画布内容60fps时呈现。

只需创建一次渐变并使用2D画布API中的变换函数移动它。

还要确保画布分辨率(画布上的像素数)与画布占用的CSS像素数相匹配。

// start the main loop when ready
requestAnimationFrame(mainLoop);
// get the canvas context
const ctx = can.getContext("2d");
// set up mouse
document.addEventListener("mousemove", mEvent);
function mEvent(e) { mouse.x = e.pageX; mouse.y = e.pageY }
const mouse = { x: 0, y: 0 };
// create gardient
const grad = ctx.createRadialGradient(0, 0, 0, 0, 0, 100);
grad.addColorStop(0, "rgb(255,255,255)");
grad.addColorStop(1, "rgb(0,0,0)");
// requestAnimationFrame callback function
function mainLoop() {
  // resize canvas if needed
  if (can.width !== innerWidth || can.height !== innerHeight) {
    can.width = innerWidth; // resize canvas if 
    can.height = innerHeight; // window resized
  }
  // set canvas origin to the mouse coords (moves the gradient)
  ctx.setTransform(1, 0, 0, 1, mouse.x, mouse.y);
  ctx.fillStyle = grad;
  // fill canvas with a rectangle
  ctx.fillRect(-mouse.x, -mouse.y, can.width, can.height);
  requestAnimationFrame(mainLoop);
}
canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}
<canvas id="can"></canvas>