htmlcanvasshadow

html canvas shadow being applied to everything


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


Solution

  • 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)