clipping - How can I clip INSIDE a shape in HTML5 canvas? -


i've found number of examples clipping outside region of arc (e.g.: this example). can't seem figure out how clip inside arc shape instead.

here example of how i'm clipping outside region, opposite of want:

ctx.save();  ctx.beginpath(); ctx.arc(x, y, radius, 0, math.pi * 2, false); ctx.clip();  ctx.beginpath(); ctx.linewidth     = 1; ctx.shadowblur    = 10; ctx.shadowoffsetx = shadowoffset; ctx.shadowcolor   = '#000000'; ctx.strokestyle   = '#000000'; ctx.arc(x, y, radius, 0, math.pi * 2, false); ctx.stroke();  ctx.restore(); 

available options

for irregular shapes can use 2 techniques:

  1. composite mode
  2. clipping

imho better choice use actual clipping mode or composite mode destination-out.

as marke says in answer xor available too, xor inverts alpha pixels , doesn't remove rgb pixels. works solid images no transparency, have existing pixels transparency these might give opposite effect (becoming visible) or if later use xor mode else drawn on top "clipped" area show again.

clipping

by using clipping can use clearrect clear area defined path.

example:

/// save context clipping ctx.save();  /// create path ctx.beginpath(); ctx.arc(x, y, radius, 0, 2 * math.pi); ctx.closepath();  /// set clipping mask based on shape ctx.clip();  /// clear inside ctx.clearrect(0, 0, offset, offset);  /// remove clipping mask ctx.restore(); 

online demo clipping

source image: image has partial semi-transparent pixels , full transparent white background comes through -

source image

result:

we punched hole in , background shows through:

clipping

composite mode: destination-out

using composite mode destination-out clear pixels clipping:

ctx.beginpath(); ctx.arc(offset * 0.5, offset * 0.5, offset * 0.3, 0, 2 * math.pi); ctx.closepath();  /// set composite mode ctx.globalcompositeoperation = 'destination-out'; ctx.fill();  /// reset composite mode default ctx.globalcompositeoperation = 'source-over'; 

online demo composite mode:

result:

destination out

same clipping destination-out removes pixels.

composite mode: xor

using xor in case there exists transparent pixels (see online example here):

xor mode

only alpha values inverted. don't have solid pixels alpha won't go 255 0 (255 - 255) 255 - actual value result in non-cleared background using mode.

(if draw second time same mode "removed" pixels restored can utilized in other ways).


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -