Hard Rain
Hard Rain

Reputation: 1410

HTML5 canvas: only outer shadow

If I draw a rectangle to the canvas, and I enable the shadows, then there will be created inner, and outer shadows too, but I only want outer shadow.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.shadowColor = 'black';
ctx.shadowBlur = 5;

ctx.strokeRect(20,30,150,75);

The only way I've found is ctx.clearRect(20,30,150,75);. But it's not really what I want, because there may be something under my rect, and I don't want to delete it.

Thanks in advance,

Upvotes: 2

Views: 2257

Answers (2)

Warren R.
Warren R.

Reputation: 497

You can also use .fillRect() instead of .strokeRect(). This will create a solid rectangle that has an inner color you define as .fillStyle()

ctx.shadowColor = 'black';
ctx.fillStyle = 'white';
ctx.shadowBlur = 5;
ctx.fillRect(20,30,150,75);

You will still have the problem of it overwriting whatever was underneath the rectangle, so you would still need pimvdb's solution to solve that problem.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154828

You could fetch the pixels inside the rectangle, do the painting and put those pixels back. That way, pixels inside the rectangle won't change: http://jsfiddle.net/dkAKE/.

var imgdata = ctx.getImageData(20, 30, 150, 75);
ctx.strokeRect(20, 30, 150, 75);
ctx.putImageData(imgdata, 20, 30);

To retain the border, use (21, 31, 148, 73) as the area (assuming a stroke width of 1px).

Upvotes: 4

Related Questions