views:

29

answers:

1

I have a semi-transparent shape:

ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
ctx.beginPath();  
ctx.moveTo(0, 150);  
ctx.lineTo(300, 0);  
ctx.lineTo(300, 450);
ctx.lineTo(50, 500);
ctx.closePath();
ctx.fill();

I want to add a bit of shadow, but I want it to only appear outside of the shape, I guess more of a glow than a shadow. Is there a way to do this in canvas as my attempts with:

ctx.shadowBlur    = 5;
ctx.shadowColor   = 'rgba(0, 0, 0, 0.25)';

look fairy ordinary as the dark shadow is visible through the semi-transparent shape.

Thanks!

A: 

I think the easiest way to do this is create a clipping region that includes everything outside the shape and then draw the shadow there.

There is a description of creating inverted clip regions here: forums.whatwg.org.

Basically, for you the steps would be:

ctx.save();  // store initial clip region

ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, canvas.width);
ctx.lineTo(canvas.height, canvas.width);
ctx.lineTo(canvas.height, 0);
ctx.lineTo(0, 0);
// {subpath of your shape here}
ctx.clip()

Then enable shadows and drap your shape.

Restore the initial clip region:

ctx.restore()

Then without shadows, draw your shape as normal.

andrewmu