19

If you define a shadow ONCE, then it applies to all "graphics" on the canvas from thereon after (which is what it's supposed to do).

Sample: http://flanvas.com/development/flanvas/test.html

Does anyone know best practice to turn the shadow off after you've used it? I'm setting shadowColor to "rgba(0,0,0,0)" which is a no-alpha black. I'm sure there is a better way.

case sample: The text is also getting a shadow. I'm using the no-alpha black to combat this for now. http://flanvas.com/development/flanvas/examples/filters-dropShadowFilter.html

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

4 Answers4

33

By using save, translate and restore you can perform your tasks without worrying about the style changes, for eg.

ctx.save();
ctx.translate(X,Y);

ctx.shadowColor = 'rgba(255, 0, 0, 0.5)';

// do some stuff

ctx.restore();

here X & Y are the co-ordinates where you intended to draw and you do your stuff relative to the co-ordinates 0,0.

This method solves the problem of caching and restoring the previous styles/values and is also very helpful when you work with gradients as they are always plotted relative to the origin (0,0)

Livingston Samuel
  • 2,422
  • 2
  • 20
  • 35
  • 1
    Excellent point. This solution works really nicely in more complex cases (less things to keep track of). – Juho Vepsäläinen Jan 20 '11 at 15:03
  • @Livingston Samuel, do you know if this has any effect on performance? – Jona Apr 12 '20 at 16:18
  • there are performance implications of using `save` and `restore`, especially when used in the main loop. If performance is primary focus, using an offscreen canvas to render and using that as a sprite would be better. If you want to only set the transform origin, then using `setTransform` instead would be better. – Livingston Samuel Jul 15 '20 at 07:27
11

(EDIT: Oops! I see that's what you were already doing with a 0 alpha black.)

This is what you were looking for:

context.shadowColor = "transparent";
Hugh Man
  • 111
  • 1
  • 3
6

It's usually a good idea to store the old value of these kind of "global" attributes before you change it and use this stored value to restore it later on. Example:

var origShadowColor = ctx.shadowColor;
ctx.shadowColor = 'rgba(255, 0, 0, 0.5)';

// ... do some stuff

ctx.shadowColor = origShadowColor;
Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
0

I created a function i can call to reset the shadow if needed.

resetShadow() {
    this.ctx.shadowOffsetX = 0;
    this.ctx.shadowOffsetY = 0;
    this.ctx.shadowColor = "transparent";
}
Judson Terrell
  • 4,204
  • 2
  • 29
  • 45