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(它只是一个临时画布)。然后将阴影画布绘制到主画布上。这要快得多,因为影子计算不需要每秒多次。你所做的只是将一个预建的画布复制到可见的画布上。

StackOverflow 文档

<!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>