javascript - canvas - Substract shape from a clipped canvas -
i want clip annulus (i.e. ring) image via javascripts canvas. have approach think inelegant (and dont understand why works, , why doesnt result in smaller circle).
context.drawimage(imageobj, 0, 0, 500, 500); //crop outer circle context2.beginpath(); context2.arc(250, 250, 200, 0, 2 * math.pi, false); context2.closepath(); context2.clip(); //draw circle context2.drawimage(canvas,0,0); //crop inner circle context2.beginpath(); context2.arc(250, 250, 100, 0, 2 * math.pi, false); context2.closepath(); context2.clip(); //clear context 2 context2.clearrect(0,0,500,500) // draw annulus context2.drawimage(canvas2,0,0);
is there better way this?
this work because clipping areas called clip
method stack.
imo, indeed not best way it, need call ctx.save();
before clipping , ctx.restore()
afterward, heavy methods.
my preferred way use compositing :
var ctx = canvas.getcontext('2d'); var imageobj = new image(); imageobj.onload = function() { ctx.drawimage(imageobj, 0, 0, 500, 500); // keep outer circle ctx.globalcompositeoperation = 'destination-in'; ctx.beginpath(); ctx.arc(250, 250, 200, 0, 2 * math.pi, false); ctx.fill(); // remove inner 1 ctx.globalcompositeoperation = 'destination-out'; ctx.beginpath(); ctx.arc(250, 250, 100, 0, 2 * math.pi, false); ctx.fill(); // reset gco ctx.globalcompositeoperation = 'source-over'; }; imageobj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
<canvas id="canvas" width="500" height="500"></canvas>
Comments
Post a Comment