Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've seen this question before but the answers given are for canvas images that have been drawn on via path however, i'm drawing an image.

Is it possible to create an inset-shadow?

context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 10;
context.shadowColor = 'rgba(30,30,30, 0.4)';

var imgOne = new Image();
imgOne.onload = function() {
    context.drawImage(imgOne, 0, 0);
};
imgOne.src = "./public/circle.png";

So I draw the circle picture on. I've now at the moment got a slight shadow on the outside of the circle, how can I get this inset instead of offset?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

Composition chain

Use a series of composite + draw operation to obtain inset shadow.

Note: the solution require exclusive access to the canvas element when created so either do this on an off-screen canvas and draw back to main, or if possible, plan secondary graphics to be drawn after this has been generated.

The needed steps:

  • Draw in original image
  • Invert alpha channel filling the canvas with a solid using xor composition
  • Define shadow and draw itself back in
  • Deactivate shadow and draw in original image (destination-atop)

Result

var ctx = c.getContext("2d"), img = new Image;
img.onload = function() {

  // draw in image to main canvas
  ctx.drawImage(this, 0, 0);

  // invert alpha channel
  ctx.globalCompositeOperation = "xor";
  ctx.fillRect(0, 0, c.width, c.height);

  // draw itself again using drop-shadow filter
  ctx.shadowBlur = 7*2;  // use double of what is in CSS filter (Chrome x4)
  ctx.shadowOffsetX = ctx.shadowOffsetY = 5;
  ctx.shadowColor = "#000";
  ctx.drawImage(c, 0, 0);

  // draw original image with background mixed on top
  ctx.globalCompositeOperation = "destination-atop";
  ctx.shadowColor = "transparent";                  // remove shadow !
  ctx.drawImage(this, 0, 0);
}
img.src = "http://i.imgur.com/Qrfga2b.png";
<canvas id=c height=300></canvas>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...