Skip to content
Advertisement

How to create a common shadow for multiple strokes in a single canvas?

I’m trying to draw multiple strokes on a canvas and I’d like them to have a common shadow. Currently the cast shadows on one another which is not what I want.

Ideal result

ideal result

What I’ve tried

  • Creating shadow using ctx.shadowColor jsfiddle
  • Creating shadow using ctx.filter jsfiddle
  • Creating shadow using css box-shadow on the canvas — draws shadow on the whole box
  • Creating shadow using css filter on the canvas — draws shadow on the whole box

Advertisement

Answer

You can use Path2D and add all your segments to one path, then do the stroke to that path.

Here is your jsfiddle using ctx.filter with my recommendation.

const segments = [
 [{x: 10, y: 50}, {x: 50, y: 50}],
 [{x: 50, y: 10}, {x: 50, y: 50}],
 [{x: 90, y: 50}, {x: 50, y: 50}],
 [{x: 50, y: 90}, {x: 50, y: 50}],
]

let path = new Path2D()
segments.forEach(segment => {  
  path.moveTo(segment[0].x, segment[0].y)
  path.lineTo(segment[1].x, segment[1].y)  
})

const ctx = document.getElementById('my-canvas').getContext('2d')
ctx.lineWidth = 5
ctx.filter = 'drop-shadow(-3px -3px 3px #f00)';
ctx.strokeStyle = 'black'
ctx.stroke(path)
<canvas width="100" height="100" id="my-canvas" style="background: #00ff00"/>

You can read more about Path2D here:
https://developer.mozilla.org/en-US/docs/Web/API/Path2D/Path2D

Advertisement