2017-10-10 83 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>