2017-04-23 68 views
0

我做了一個漫反射動畫,並使用RequestAnimationFrame來實現它。我嘗試了數百次來改進我的程序。但它不工作!!!我的錯在哪裏?如何正確使用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的屬性normally.Function渲染,以使圓形越來越lighter.Newly描畫圓越來越bigger.Small回合正成爲一次又一次地使用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); 

另外,當canvas動畫向上移動時,如何恢復背景?

+0

你跟在問題'javascript'遇到了什麼問題? – guest271314

+0

@ guest271314第一個程序不顯示任何內容,第二個程序可以正確顯示動畫。兩者之間的區別在於第一個程序不僅僅是函數調用。 –

+0

請參閱http://stackoverflow.com/help/mcve – guest271314

回答

0

調整你的draw_point功能就像這樣。你目前正在執行render功能是什麼馬上要參考傳遞給​​,不插入函數調用有

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