I have a text that's drawn on a HTML5 canvas. How do I clip or hide part of the text that is to the left of a line?
In this example, the part of the word 'HELLO' is clipped to the left of the red line.
There are two restrictions:
We can split the text string by the line breaks and position the split text in a way that each piece of text is on a separate line. to add the canvas. to add the txt text into the canvas.
HTML canvas clip() Method Clip of a rectangular region of 200*120 pixels from the canvas. Then, draw a red rectangle. Only the part of the red rectangle that is inside the clipped area is visible: YourbrowserdoesnotsupporttheHTML5canvastag.
clip() The CanvasRenderingContext2D. clip() method of the Canvas 2D API turns the current or given path into the current clipping region. The previous clipping region, if any, is intersected with the current or given path to create the new clipping region.
An alternative to Jarrod’s useful technique is using a clipping region when drawing your text.
For example if your y-axis is at 30px, this clip will not draw text to the left of 30px
ctx.rect(30,0,canvas.width-30,canvas.height);
ctx.clip();
Then fillText
will leave anything left of your y-axis undisturbed (resulting in your “-ELLO”)
ctx.fillText(theText,20,50);
Here’s code and a Fiddle: http://jsfiddle.net/m1erickson/Q5Pfa/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
clipTextToGrid(50,"HELLO","48px verdana");
function clipTextToGrid(leftAxisBorder,theText,font){
ctx.save();
ctx.beginPath();
ctx.rect(leftAxisBorder,0,canvas.width-leftAxisBorder,canvas.height);
ctx.clip();
ctx.font=font;
ctx.fillText(theText,3,50);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
You could draw your text to an off screen canvas (that being a new canvas that is in memory), then draw that canvas to your main canvas, applying your clipping.
This will allow you to draw any part of your offscreen canvas, such as "clipping" it to get the effect you're after. This can be done with regular drawImage
method:
ctx.drawImage([x: adjust for clipping], y, w, h, sourceCanvas, 0, 0, w, h);
You'll of course have to cacluate how much to clip.
Hope that makes sense!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With