The problem what I have is that React TS throws an error for my window.webkitRequestAnimationFrame
and window.mozRequestAnimationFrame
thinking that I mean 'requestAnimationFrame'
instead. Should I replace it with something else?
App.tsx
import React from "react";
export interface Props {
canvas: HTMLElement;
particles: number;
}
function App(props: Props) {
props.canvas = document.getElementById("canvas");
var ctx = props.canvas.getContext("2d");
props.particles = [];
props.canvas.onmousedown = function (e: any) {
for (var i = 0; i < 36 * 2; i ) {
props.particles.push({
x: e.clientX,
y: e.clientY,
angle: i * 5,
size: 5 Math.random() * 3,
life: 200 Math.random() * 50,
});
}
};
props.canvas.onmouseup = function () {
//ctx.clearRect(0, 0, 600, 600);
};
var delta = 0;
var last = Date.now();
function animate() {
delta = Date.now() - last;
last = Date.now();
for (var i = 0; i < props.particles.length; i ) {
var p = props.particles[i];
p.x = Math.cos(p.angle) * 4 Math.random() * 2 - Math.random() * 2;
p.y = Math.sin(p.angle) * 4 Math.random() * 2 - Math.random() * 2;
p.life -= delta;
p.size -= delta / 50;
if (p.size <= 0) {
p.life = 0;
}
if (p.life <= 0) {
props.particles.splice(i--, 1);
continue;
}
}
}
function render() {
ctx.fillStyle = "#00FF00";
for (var i = 0; i < props.particles.length; i ) {
if (Math.random() < 0.1) {
continue;
}
var p = props.particles[i];
ctx.beginPath();
ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2, false);
ctx.fill();
}
}
window.requestAnimFrame = (function () {
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
}
);
})();
(function animloop() {
requestAnimFrame(animloop);
animate();
render();
})();
return <canvas id="canvas" width="100vw" height="100vh"></canvas>;
}
export default App;
Edit: Edited to only ask one question instead of many in this thread.
CodePudding user response:
requestAnimationFrame()
has been available in all major browsers for years by now. According to that link, it looks like the last browser releases that included the prefixed version were release 2012-2014.
So it's probably safe to use requestAnimationFrame
directly, and then you can remove the polyfill altogether.