shadowColor shadowBlur shadowOffsetX shadowOffsetY(路徑樣式屬性)
shadowColor = color // CSS color
shadowBlur = width // integer blur width
shadowOffsetX = distance // shadow is moved horizontally by this offset
shadowOffsetY = distance // shadow is moved vertically by this offset
這組屬性將在路徑周圍新增陰影。
填充路徑和描邊路徑都可能有陰影。
陰影在路徑周邊是最暗的(不透明的),並且當它遠離路徑周邊時變得越來越淺。
- shadowColor 指示將使用哪種 CSS 顏色來建立陰影。
- shadowBlur 是陰影從路徑向外延伸的距離。
- shadowOffsetX 是陰影水平移動遠離路徑的距離。正距離向右移動陰影,負距離向左移動陰影。
- shadowOffsetY 是陰影垂直移動遠離路徑的距離。正距離向下移動陰影,負距離向上移動陰影。
關於 shadowOffsetX&shadowOffsetY
重要的是要注意整個陰影的整體移動。這將導致部分陰影在填充路徑下移動,因此部分陰影將不可見。
關於陰影筆畫
遮蔽筆劃時,筆劃的內部和外部都會被遮蔽。中風時陰影最暗,當陰影從中風向兩個方向向外延伸時,陰影變亮。
完成時關閉陰影
繪製陰影后,可能需要關閉陰影以繪製更多路徑。要關閉陰影,請將 shadowColor
設定為透明。
context.shadowColor = 'rgba(0,0,0,0)';
效能考慮因素
陰影(如漸變)需要大量計算,因此你應該謹慎使用陰影。
動畫時要特別小心,因為每秒多次繪製陰影會對效能產生很大影響。如果需要為陰影路徑設定動畫,則解決方法是在第二個陰影畫布上預先建立陰影路徑。陰影畫布是使用 document.createElement
在記憶體中建立的普通畫布 - 它不會新增到 DOM(它只是一個臨時畫布)。然後將陰影畫布繪製到主畫布上。這要快得多,因為影子計算不需要每秒多次。你所做的只是將一個預建的畫布複製到可見的畫布上。
<!doctype html>
<html>
<head>
<style>
body{ background-color:white; }
#canvas{border:1px solid red; }
</style>
<script>
window.onload=(function(){
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// shadowed stroke
ctx.shadowColor='black';
ctx.shadowBlur=6;
ctx.strokeStyle='red';
ctx.strokeRect(50,50,100,50);
// darken the shadow by stroking a second time
ctx.strokeRect(50,50,100,50);
// shadowed fill
ctx.shadowColor='black';
ctx.shadowBlur=10;
ctx.fillStyle='red';
ctx.fillRect(225,50,100,50);
// darken the shadow by stroking a second time
ctx.fillRect(225,50,100,50);
// the shadow offset rightward and downward
ctx.shadowColor='black';
ctx.shadowBlur=10;
ctx.shadowOffsetX=5;
ctx.shadowOffsetY=5;
ctx.fillStyle='red';
ctx.fillRect(50,175,100,50);
// a wider blur (==extends further from the path)
ctx.shadowColor='black';
ctx.shadowBlur=35;
ctx.fillStyle='red';
ctx.fillRect(225,175,100,50);
// always clean up! Turn off shadowing
ctx.shadowColor='rgba(0,0,0,0)';
}); // end window.onload
</script>
</head>
<body>
<canvas id="canvas" width=400 height=300></canvas>
</body>
</html>