Answer the question
In order to leave comments, you need to log in
Does animation consume a lot of CPU power?
Hello, my cursor animation code is very CPU intensive, please help to optimize
https://wonderful-raman-802281.netlify.com/
<div class="wrap">
<div id="ball"></div>
</div>
<div id="qwe"></div>
var $ = document.querySelector.bind(document);
var $on = document.addEventListener.bind(document);
var xmouse, ymouse;
$on("mousemove", function(e) {
xmouse = e.clientX || e.pageX;
ymouse = e.clientY || e.pageY;
});
var ball = $("#ball");
var x = void 0,
y = void 0,
dx = void 0,
dy = void 0,
tx = 0,
ty = 0,
key = -1;
var followMouse = function followMouse() {
key = requestAnimationFrame(followMouse);
if (!x || !y) {
x = xmouse;
y = ymouse;
} else {
dx = (xmouse - x) * 0.25;
dy = (ymouse - y) * 0.25;
if (Math.abs(dx) + Math.abs(dy) < 0.1) {
x = xmouse;
y = ymouse;
} else {
x += dx;
y += dy;
}
}
ball.style.left = x + "px";
ball.style.top = y + "px";
var back = $("#qwe");
var sw = screen.width;
back.style.width = 54 - x / (sw * 0.125) + "%";
var historicTouchX = null;
setInterval(function(e) {
historicTouchX = x;
var speed = (historicTouchX - xmouse) / 20;
if (Math.abs(speed) >= 2) {
ball.style.width = 33 + "px";
ball.style.height = 33 + "px";
} else {
ball.style.width = 45 + "px";
ball.style.height = 45 + "px";
}
}, 2);
};
#ball {
width: 45px;
height: 45px;
background: none;
border: 2px solid black;
border-radius: 50%;
position: absolute;
left: 50%;
top: 50%;
margin: -22.5px 0 0 -22.5px;
pointer-events: none;
-webkit-transition: color 0.5s, width 0.3s, height 0.3s, margin 0.3s,
border-width 0.5s;
-o-transition: color 0.5s, width 0.3s, height 0.3s, margin 0.3s,
border-width 0.5s;
-moz-transition: color 0.5s, width 0.3s, height 0.3s, margin 0.3s,
border-width 0.5s;
transition: color 0.5s, width 0.3s, height 0.3s, margin 0.3s,
border-width 0.5s;
will-change: color, width, height, margin, border-with, transform;
}
#qwe {
background-color: wheat;
height: 100vh;
width: 46%;
z-index: 999999999;
}
Answer the question
In order to leave comments, you need to log in
setInterval() inside requestAnimationFrame()
use the (delay checks) key variable for this
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question