Canvas How to - Create Different shadow for stroke and fill on canvas








Question

We would like to know how to create Different shadow for stroke and fill on canvas.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from   w w w  .  ja  v  a 2 s . c o m-->
    var canvas = document.getElementById('c');
    var ctx = canvas.getContext('2d');
    ctx.save();
    ctx.fillStyle = "blue";
    ctx.strokeStyle  = "black";
    ctx.lineWidth="20";
    ctx.beginPath();  
    ctx.moveTo(300, 100);  
    ctx.lineTo(400, 100);  
    ctx.lineTo(400, 200);
    ctx.lineTo(300, 200);
    ctx.closePath();
    ctx.shadowColor = "rgba(0,255,0, 1)";
    ctx.shadowOffsetX = 50; 
    ctx.shadowOffsetY = 50;
    ctx.stroke();
    ctx.fill();
    // clear the shadow
    ctx.shadowColor = 0;
    ctx.shadowOffsetX = 0; 
    ctx.shadowOffsetY = 0;
    // restroke without the shaodw
    ctx.stroke();
}//]]>  
</script>
</head>
<body>
  <canvas id="c" width="800" height="600"></canvas>
</body>
</html>

The code above is rendered as follows: