Last updated 2 years ago
Was this helpful?
browser ⟩ canvas ⟩ state ⟩ clipping
when .clip() is called, current clipping region = current path clipped to current clipping region.
there's no way to reset clipping region, call .save(), .restore() instead.
CanvasRenderingContext2D ⟩
.clip()
💾 replit:canvas clipping
⬆️ require: drawOnCanvas2D(), Vector, Rect, regular polygons
drawOnCanvas2D('#playground', (c) => { // drawing settings const center = vec(200, 225); // triangle center const R = 200, r = 80; // radii (large/small) // text const text = "<canvas>"; const textHeight = (R - r)/2; c.font = `bold ${textHeight}pt sans-serif`; // Big font const textWidth = c.measureText(text).width; const textCenter = center.plus(0, R / 2 - R / 16); const textRect = Rect.withCenter(textCenter, vec(textWidth/2, textHeight/2)); c.strokeRect(...textRect.coords); c.strokeText(text, ...textRect.bottomLeft.coords); // vertical stripe down the middle const stripCenter = center.plus(0, -R/4); // center of triangle height const stripHalfDimension = vec(40, .85*R); const strip = Rect.withCenter(stripCenter, stripHalfDimension); c.strokeRect(...strip.coords); // create path for clipping region c.polygon(3, ...center.coords, R); c.polygon(3, ...center.coords, r, { clockwise: false }); // ⭐ make that path the clipping region c.clip(); c.fillStyle = 'hsl(0 80% 10% / 0.05)'; c.fill(); c.stroke(); // ⭐ half of line width will be clipped away // fill strip (inside the clipping region) c.fillStyle = "hsl(270 80% 50% / 0.8)"; c.fillRect(...strip.coords); // fill text (inside the clipping region) c.fillStyle = "hsl(330 80% 50% / 0.8)"; c.fillText(text, ...textRect.bottomLeft.coords); });