2016-12-13 54 views
0

我创建SVG,我想转换svg到画布。 我做到以下几点:帆布Path2d内阴影

var canvas = document.getElementById("canvas"); 
var ctx = canvas.getContext("2d"); 
var p = new Path2D("M10 10 h 80 v 80 h -80 Z"); 
ctx.fillStyle = '#cb1a2f'; 
ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; 
ctx.shadowBlur = 24; 
ctx.fill(p); 

但我想使正方形内阴影。我有一个完全不同的图SVG。这个SVG纯粹就是一个例子。

+0

@Kaiido它只是移动的影子,我需要把它里面的造型 – annex

回答

0

影都内和形状外帆布API:

var canvas = document.querySelector("canvas"); 
 
var ctx = canvas.getContext("2d"); 
 
ctx.strokeStyle = 'white'; 
 
ctx.shadowColor = "black"; 
 
ctx.shadowBlur = 10; 
 
ctx.strokeRect(20,20,50,50);
<canvas></canvas>

但填写和中风在这个阴影的顶部渲染。

所以你可以做的是首先填充你的形状,然后将上下文的globalCompositeOperation属性设置为source-atop,这样新的绘图只保存在我们已经绘制了某些东西的地方,最后调用你的路径。

var canvas = document.querySelector("canvas"); 
 
var ctx = canvas.getContext("2d"); 
 
var p = new Path2D("M10 10 h 80 v 80 h -80 Z"); 
 
ctx.fillStyle = ctx.strokeStyle = 'red'; 
 
// fill a first time 
 
ctx.fill(p); 
 
// change the gCO 
 
ctx.globalCompositeOperation = "source-atop"; 
 
ctx.shadowColor = "green"; 
 
ctx.shadowBlur = 14; 
 
// now stroke to get the inner shadow 
 
ctx.stroke(p); 
 

 
// reset the gCO to its default 
 
ctx.globalCompositeOperation = "source-over";
<canvas></canvas>