canvas - 我在哪里放clearRect来刷新动画?

时间:2018-01-26 20:38:19

标签: javascript html5 html5-canvas

我迷路了,可以帮忙。

我试图让曲线的顶点跟随鼠标,但找不到我应该刷新的地方,也不知道为什么。

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);

    });

}

这是一个codepen - https://codepen.io/anon/pen/xpvaee

任何指导意见。

1 个答案:

答案 0 :(得分:1)

动画,渲染和IO事件。

  1. 您必须将鼠标事件与渲染分开,因为鼠标以不同于显示更新的速率触发事件。

  2. 您不应该在鼠标或动画事件中查询DOM。您应该只在需要时查询DOM。在应用程序开始时,以及有影响状态的更改时,例如调整大小事件

  3. requestAnimationFrame(rAF)与显示速率同步(每秒60次)。你在动画函数中放置rAF并不重要。

  4. 按可见度顺序渲染,先渲染背景,然后渲染到最后一个最顶层的对象。

  5. jQuery很慢,99.99%的时候使用标准API更容易。尽量避免使用jQuery,这是一个古老的恐龙,它已经过了日期。使用它会阻止您了解如何最好地使用DOM。

  6. 因此,从上面的点开始,您的代码看起来应该更像。 (没有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);
    
    }
    
相关问题