Reputation: 117
For example context.fillText("foobar",30,0);
would render the full text "foobar" 30 pixels down, but how could I keep the rightmost 20 pixels, to throw out a random number, from rendering? One solution for this is to render a white box immediately after to hide the rest of foobar. But this solution isn't compatible with other features I want to incorporate. I need a way to really keep the rest of foobar from rendering in the first place. Is this possible in canvas or would I need to use another graphics API?
Upvotes: 0
Views: 338
Reputation: 16896
.clip()
allows you to use paths to form a mask. This, combined with the various path methods, would allow you to draw a clipped version of your text.
An example, from the MDN page, uses a circle to mask a rectangle:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Create circular clipping region
ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2);
ctx.clip();
// Draw stuff that gets clipped
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);
<canvas id="canvas"></canvas>
Upvotes: 1