2014-03-31 45 views
3

是否可以將CSS動畫(在我的情況下是一種發光效果)應用於通過javascript在畫布上繪製的圓圈?在繪製的畫布元素上應用CSS

我用這angularjs指令:https://github.com/angular-directives/angular-round-progress-directive/blob/master/angular-round-progress-directive.js

我使用它作爲一個計數器,我希望它煥發每秒(得到了動畫已經CSS代碼

這是可能的 ?另一個想法是,使畫布本身爲圓形,並將發光效果應用到畫布上。

回答

3

不能將CSS應用於畫布中繪製的元素,因爲它們不存在於DOM上。就好像它們是位圖圖像一樣。

你可以使用一個SVG circle,雖然,這將讓你style the circle CSS和使用動畫:

<svg height="100" width="100"> 
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> 
</svg> 
5

不能應用CSS來吸引到畫布上的形狀,但你可以通過簡單地創建發光效果影子。

A demo here

var canvas = document.getElementById('canvas'), // canvas 
    ctx = canvas.getContext('2d'),    // context 
    w = canvas.width,       // cache some values 
    h = canvas.height, 
    cx = w * 0.5, 
    cy = h * 0.5, 
    glow = 0,         // size of glow 
    dlt = 1,         // speed 
    max = 40;         // max glow radius 

ctx.shadowColor = 'rgba(100, 100, 255, 1)';  // glow color 
ctx.fillStyle = '#fff';       // circle color 

function anim() { 
    ctx.clearRect(0, 0, w, h);     // clear frame 
    ctx.shadowBlur = glow;      // set "glow" (shadow) 

    ctx.beginPath();       // draw circle 
    ctx.arc(cx, cy, cx * 0.25, 0, 6.28); 
    ctx.fill();         // fill and draw glow 

    glow += dlt;        // animate glow 
    if (glow <= 0 || glow >= max) dlt = -dlt; 

    requestAnimationFrame(anim);    // loop 
} 
anim(); 

example

更新

要獲得與外發光綱要,你可以簡單地 「衝出來」 使用複合操作的圓心。這裏的示例使用保存/恢復去除陰影 - 可以通過手動復位這些優化代碼 - 但爲了簡單起見,做以下修改:

ctx.fillStyle = '#fff'; 
// remove shadow from global 

function anim() { 
    ctx.clearRect(0, 0, w, h); 

    // draw main circle and glow 
    ctx.save();         // store current state 
    ctx.shadowColor = 'rgba(100, 100, 255, 1)'; 
    ctx.shadowBlur = glow; 

    ctx.beginPath(); 
    ctx.arc(cx, cy, cx * 0.25, 0, 6.28); 
    ctx.fill();  
    ctx.restore();        //restore -> removes the shadow 

    // draw inner circle 
    ctx.globalCompositeOperation = 'destination-out'; // removes what's being drawn 
    ctx.beginPath(); 
    ctx.arc(cx, cy, cx * 0.23, 0, 6.28);   // smaller filled circle 
    ctx.fill();  
    ctx.globalCompositeOperation = 'source-over'; // reset 

    glow += dlt; 
    if (glow <= 0 || glow >= max) dlt = -dlt; 

    requestAnimationFrame(anim); 
} 

所述的複合操作將在下一次繪製操作除去的像素。只需在頂部繪製一個較小的實心圓,這將會留下第一個圓的輪廓及其發光。

Modified fiddle here

example2

+0

這是真正有用的!不幸的是,我不能將它應用於我的樣本。你介意幫助我解決這個問題嗎?我只想在外圈上發光效果 - 但我能得到的是對所有圈子都有發光效果 - 但沒有動畫效果:(請參閱我的git:https://github.com/manulitopetito/angular-progress – ManuKaracho

+0

還在嘗試(連續3小時......),但沒有運氣..在第二個畫布上畫外圈會更好嗎? – ManuKaracho

+0

@ user2556555(後期解答 - >時區差異)當然,但是您可以設置一個小提琴,因爲我不知道你的代碼,只是放在必要的部分,我會看一看,實質上:你可以在用複合模式繪製它之後「戳」出圓的中心(設置globalCompositeOperation模式到目的地輸出,並在禁用陰影的情況下在頂部繪製一個較小的圓圈,將回退模式設置爲源代碼結束)請參閱此模塊:http://jsfiddle.net/4BdGQ/1/ – K3N