如何正确使用RequestAnimationFrame?

时间:2017-04-23 16:39:02

标签: javascript html5 canvas

我制作了一个漫反射动画,并使用RequestAnimationFrame来实现它。我尝试了数百次来改进我的程序。但是它不起作用!!!哪里错了?

function draw_point(x, y){
    x += 10.5;
    y += 10.5;
    radius = 0;
    var context = $("#canvas_graph")[0].getContext('2d');
    window.webkitRequestAnimationFrame(render(x, y, radius, context));
};

function drawCircle(x, y, radius, context){
    context.beginPath();
    context.arc(x, y, radius, 0, Math.PI * 2);
    context.closePath();
    context.lineWidth = 2;
    context.strokeStyle = 'red';
    context.stroke();
    radius += 0.2;

    if (radius > 10) {
        radius = 0;
        }
};

//The effect of diffusion is achieved by changing the attribute
function render(x ,y, radius, context){
    return function step(){
        var prev = context.globalCompositeOperation;
        context.globalCompositeOperation = 'destination-in';
        context.globalAlpha = 0.95;
        context.fillRect(0, 0, 890, 890);
        context.globalCompositeOperation = prev;
        drawCircle(x, y, radius,context);

        window.webkitRequestAnimationFrame(step);
    };  
};
draw_point(100, 100);

但是这可以正常使用。函数通过globalAlpha属性渲染,以便圆圈变得更亮。新绘制的圆圈变得越来越大。通过一次又一次地使用globalAlpha属性,小圆变得越来越轻。

var context = $("#canvas_graph")[0].getContext('2d');
var radius = 0;
var x = 100;
var y = 100;
function drawCircle(){
    context.beginPath();
    context.arc(x, y, radius, 0, Math.PI * 2);
    context.closePath();
    context.lineWidth = 2;
    context.strokeStyle = 'red';
    context.stroke();
    radius += 0.2;

if (radius > 10) {
    radius = 0;
    }
};
function render(){
    var prev = context.globalCompositeOperation;
    context.globalCompositeOperation = 'destination-in';
    context.globalAlpha = 0.95;
    context.fillRect(0, 0, 890, 890);
    context.globalCompositeOperation = prev;
    drawCircle();

    window.webkitRequestAnimationFrame(render);
};
window.webkitRequestAnimationFrame(render);

另外,当画布动画向上移动时,如何恢复背景?

1 个答案:

答案 0 :(得分:0)

像这样调整draw_point功能。您当前正在执行render函数,您希望传递对requestAnimationFrame的引用,而不是在那里插入函数调用

function draw_point(x, y){
    x += 10.5;
    y += 10.5;
    radius = 0;
    var context = $("#canvas_graph")[0].getContext('2d');
    window.webkitRequestAnimationFrame(function() {
        render(x, y, radius, context));
    }
};