2017-10-10 128 views
0

我有一個半透明狀:帆布陰影/發光效果在半透明形狀上?

this.cx.beginPath(); 
this.cx.globalAlpha = .1; 
this.cx.fillStyle = gradientFill; 
this.cx.strokeStyle = gradientStroke; 
this.cx.arc(150, 150, 139, 0, Math.PI * 2, true); 
this.cx.lineWidth = 1; 
this.cx.stroke(); 
this.cx.fill(); 

我想補充一點影子,但我希望它只是出現在形狀外,我想更多的是光暈比陰影。有沒有辦法做到這一點在畫布我嘗試用:

this.cx.shadowColor = 'rgba(0, 0, 0, .75)'; 
this.cx.shadowBlur = 5; 
this.cx.shadowOffsetX = 5; 
this.cx.shadowOffsetY = -5; 

看童話一般的暗影通過半透明狀可見。

謝謝!

回答

0

一種方法是使用globalCompositeOperations以僅保留您的外部陰影,然後重新繪製您的半透明部分。

但是請注意,您有很多神器的噪音......

(async function() { 
 
    var ctx = c.getContext('2d'); 
 
    // commons 
 
    var gradientFill = ctx.createLinearGradient(0, 0, 200, 0); 
 
    gradientFill.addColorStop(0, 'rgba(0,0,0,0)') 
 
    gradientFill.addColorStop(1, 'rgba(255,0,0,1)') 
 
    var gradientStroke = ctx.createLinearGradient(0, 0, 200, 0); 
 
    gradientStroke.addColorStop(0, 'rgba(0,0,0,0)') 
 
    gradientStroke.addColorStop(1, 'rgba(0,255,0,1)') 
 
    ctx.lineWidth = 5; 
 
    // needed only once 
 
    ctx.beginPath(); 
 
    ctx.arc(150, 150, 139, 0, Math.PI * 2, true); 
 

 
    await wait(1000); // simply to show each step 
 

 
    // firt we draw only the shadow with black fill and stroke 
 
    ctx.shadowColor = 'rgba(0, 0, 0, .75)'; 
 
    ctx.shadowBlur = 5; 
 
    ctx.shadowOffsetX = 5; 
 
    ctx.shadowOffsetY = -5; 
 
    ctx.stroke(); 
 
    ctx.fill(); 
 

 
    await wait(1000); 
 

 
    // then keep only the shadow 
 
    ctx.globalCompositeOperation = 'destination-out'; // will erase existing content at drawn position 
 
    ctx.shadowColor = 'transparent'; // remove the shadow 
 
    ctx.stroke(); 
 
    ctx.fill(); 
 

 
    await wait(1000); 
 
    
 
    // finally draw the semi-transparent version 
 
    ctx.globalCompositeOperation = 'source-over'; 
 
    ctx.globalAlpha = .1; 
 
    ctx.fillStyle = gradientFill; 
 
    ctx.strokeStyle = gradientStroke; 
 
    ctx.stroke(); 
 
    ctx.fill(); 
 

 
})(); 
 

 
function wait(t) { 
 
    return new Promise(r => setTimeout(r, t)) 
 
}
<canvas id="c" height="300"></canvas>