2016-12-13 55 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>