Javascript 画布-我在哪里放置clearRect来刷新动画?
我迷路了,需要一些帮助 我试图让曲线的顶点跟随鼠标,但找不到应该刷新的位置,也不明白为什么Javascript 画布-我在哪里放置clearRect来刷新动画?,javascript,html,html5-canvas,Javascript,Html,Html5 Canvas,我迷路了,需要一些帮助 我试图让曲线的顶点跟随鼠标,但找不到应该刷新的位置,也不明白为什么 function animate(){ requestAnimationFrame(animate); canvas = document.querySelector('canvas'); c = canvas.getContext('2d'); //c.clearRect(0,0, canvas.width,canvas.height); $( "#canv
function animate(){
requestAnimationFrame(animate);
canvas = document.querySelector('canvas');
c = canvas.getContext('2d');
//c.clearRect(0,0, canvas.width,canvas.height);
$( "#canvas" ).mousemove(function( event ) {
topWave.draw(0, 300, event.pageX, 50, $(window).width(), 300);
});
}
这是一个密码笔-
欢迎提供任何指导。动画、渲染和IO事件。
必须将鼠标事件与渲染分开,因为鼠标触发事件的速率与显示更新的速率不同
您不应该在鼠标或动画事件中查询DOM。您应该只在需要时查询DOM。在应用程序启动时,以及当发生将影响状态的更改(如调整大小事件)时
requestAnimationFrame rAF与每秒60次的显示速率同步。在动画函数中的什么位置放置rAF并不重要
按照可见性的顺序渲染,首先渲染背景,然后渲染最顶部的对象
jQuery速度很慢,99.99%的时间使用标准API更容易。尽量避免使用jQuery,它已经过时了。使用它会阻止您学习如何最好地使用DOM
因此,从以上几点来看,您的代码应该更像。没有jQuery
// start the animation
requestAnimationFrame(animate); // this will fire when the setup code below has
// has executed
// get the DOM object
const canvas = document.querySelector('canvas');
// get the 2D context
const ctx = canvas.getContext('2d');
// create mouse object
const mouse = { x : 0, y : 0 };
// create mouse move event listener
canvas.addEventListener("mousemove",(event) => {
// each time mouse is moved update the mouse position
mouse.x = event.clientX;
mouse.y = event.clientY;
});
// Via rAF this function is called once every 1/60 of a second.
// The rate may change if you do too much rendering, or is the browser is
// busy doing something else.
function animate(){
// first thing to draw is the background, in this case that is clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// then draw your wave using the current mouse position
// innerWidth (and innerHeight) is built in global value
// same as $("window").width() but a zillion times faster
topWave.draw(0, 300, mouse.y, 50, innerWidth, 300);
// it does not matter where in this function you put rAF
// I like to put it at the bottom of the function
requestAnimationFrame(animate);
}