Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Inset-shadow on HTML5 canvas image

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...