One canvas , multiple layered content -
i have built banner multiple canvas (position: absolute, different z-idexes) but... i'd liek re-create teh whole thing 1 canvas , proves problem. banner's animation quite complex here brief question taht me understand how works.
i'd "cut" hole in black rectangle red 1 becomes visible
here code:
red.beginpath(); red.fillstyle = '#af0000'; red.fillrect(33, 33, 200, 60); // drawing red rectangle red.closepath(); red.beginpath(); red.fillstyle = '#000'; red.fillrect(77, 66, 120, 60); // drawing black 1 red.clearrect(110, 80, 20, 20); // cutting 20x20 pixels rectangle red.closepath();
i know why both rectangles affected. illustrate i'd achieve. make 2 canvas - draw red rectangle on 1 , black on another, , cut black 1 - i'd 1 canvas only. - know re-draw red part doubt that's wise solution.
here fiddle: http://jsfiddle.net/hej11px9/
thanks in advance!
i know quite amateurish question but...anyway - tried find teh solution no luck.
the answer not easy : draw hole, must clip out part of rect, when clipping meant clip in.
there's solution clip out rect : clip in whole canvas, substract inner rect going counter clockwise.
i had code 'data driven', it's easier make change.
http://jsfiddle.net/casemate/hej11px9/1/
var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext('2d'); var redrect = { x: 33, y: 33, width: 200, height: 60, color: '#af0000' }; var blackrect = { x: 77, y: 66, width: 120, height: 60, color: '#000' }; var blackrecthole = { x: 110, y: 80, width: 20, height: 20 }; var cvrect = { x: 0, y: 0, width: canvas.width, height: canvas.height }; function drawrect(rect) { ctx.beginpath(); ctx.fillstyle = rect.color; ctx.fillrect(rect.x, rect.y, rect.width, rect.height); ctx.closepath(); } function drawrectclipped(rect, cliprect) { ctx.save(); clipout(cliprect); drawrect(rect); ctx.restore(); } function clipout(cliprect) { ctx.beginpath(); rectpath(cvrect); ctx.lineto(cliprect.x, cliprect.y); rectpath_ccw(cliprect); ctx.clip(); } function rectpath(rect) { ctx.moveto(rect.x, rect.y); ctx.lineto(rect.x + rect.width, rect.y); ctx.lineto(rect.x + rect.width, rect.y + rect.height); ctx.lineto(rect.x, rect.y + rect.height); ctx.lineto(rect.x, rect.y); } function rectpath_ccw(rect) { ctx.moveto(rect.x, rect.y); ctx.lineto(rect.x, rect.y + rect.height); ctx.lineto(rect.x + rect.width, rect.y + rect.height); ctx.lineto(rect.x + rect.width, rect.y); ctx.lineto(rect.x, rect.y); } drawrect(redrect); drawrectclipped(blackrect, blackrecthole);
Comments
Post a Comment