Reputation: 555
I need some help with my script. I'm trying to make the "bright spot" move along with the mouse on my canvas
but it looks like it's moving way faster than the coursor. Where is the problem?
<!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>
Upvotes: 0
Views: 1676
Reputation: 54026
Keep the mouse events and rendering separate as mouse events are not synced to the display. Mouse events just record mouse state (up to and over 100+ samples a second.) Animation frames render only when able to display the canvas content 60fps.
Just create the gradient once and move it using the transformation functions in the 2D canvas API.
Also make sure that the canvas resolution (number pixels on the canvas) matches the number of CSS pixels the canvas occupies.
// 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>
Upvotes: 2