如何在 HTML 画布中制作阴影

Ven*_*kat 2 html javascript canvas shadow

我需要绘制一个rect带有阴影的画布,其四个侧面都有阴影rect,类似于 div 的样式为"box-shadow":"0px 0px 5px 5px"

mar*_*rkE 6

您可以使用context.shadowColorpluscontext.shadowBlur来创建box-shadow效果。

Canvas 的模糊非常浅,因此您必须经常过度绘制模糊以使其突出。

这是我的版本box-shadow: 0 0 5px 5px

在此输入图像描述

带注释的代码示例:

shadowRect(10,10,105,45,5,'red');

function shadowRect(x,y,w,h,repeats,color){
    // set stroke & shadow to the same color
    ctx.strokeStyle=color;
    ctx.shadowColor=color;
    // set initial blur of 3px
    ctx.shadowBlur=3;
    // repeatedly overdraw the blur to make it prominent
    for(var i=0;i<repeats;i++){
        // increase the size of blur
        ctx.shadowBlur+=0.25;
        // stroke the rect (which also draws its shadow)
        ctx.strokeRect(x,y,w,h);
    }
    // cancel shadowing by making the shadowColor transparent
    ctx.shadowColor='rgba(0,0,0,0)';
    // restroke the interior of the rect for a more solid colored center
    ctx.lineWidth=2;
    ctx.strokeRect(x+2,y+2,w-4,h-4);

}
Run Code Online (Sandbox Code Playgroud)

shadowRect(10,10,105,45,5,'red');

function shadowRect(x,y,w,h,repeats,color){
    // set stroke & shadow to the same color
    ctx.strokeStyle=color;
    ctx.shadowColor=color;
    // set initial blur of 3px
    ctx.shadowBlur=3;
    // repeatedly overdraw the blur to make it prominent
    for(var i=0;i<repeats;i++){
        // increase the size of blur
        ctx.shadowBlur+=0.25;
        // stroke the rect (which also draws its shadow)
        ctx.strokeRect(x,y,w,h);
    }
    // cancel shadowing by making the shadowColor transparent
    ctx.shadowColor='rgba(0,0,0,0)';
    // restroke the interior of the rect for a more solid colored center
    ctx.lineWidth=2;
    ctx.strokeRect(x+2,y+2,w-4,h-4);

}
Run Code Online (Sandbox Code Playgroud)
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

shadowRect(10,10,105,45,5,'red');

function shadowRect(x,y,w,h,repeats,color){
  // set stroke & shadow to the same color
  ctx.strokeStyle=color;
  ctx.shadowColor=color;
  // set initial blur of 3px
  ctx.shadowBlur=3;
  // repeatedly overdraw the blur to make it prominent
  for(var i=0;i<repeats;i++){
    // increase the size of blur
    ctx.shadowBlur+=0.25;
    // stroke the rect (which also draws its shadow)
    ctx.strokeRect(x,y,w,h);
  }
  // cancel shadowing by making the shadowColor transparent
  ctx.shadowColor='rgba(0,0,0,0)';
  // restroke the interior of the rect for a more solid colored center
  ctx.lineWidth=2;
  ctx.strokeRect(x+2,y+2,w-4,h-4);

}
Run Code Online (Sandbox Code Playgroud)
body{ background-color: ivory; padding:10px;}
Run Code Online (Sandbox Code Playgroud)