How to copy part of text into HTML5 canvas?

I have text that is drawn on HTML5 canvas. How to copy or hide the part of the text located to the left of the line?

In this example, part of the word "HELLO" is trimmed to the left of the red line.

There are two limitations:

  • Everything should be painted on one canvas. There are no new paintings to be created.
  • The red line in my real work is the y axis of the chart. On the left side of the red line are labels for the axis. So imagine that there are things on this side and they need to show. This part cannot be locked or erased.

enter image description here

+6
source share
3 answers

An alternative to Jarrods’s useful technique is to use the clipping area when drawing your text.

For example, if your y axis is 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 everything that remains of your y axis unperturbed (the result is "-ELLO")

 ctx.fillText(theText,20,50); 

Heres code and script: 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> 
+6
source

You can draw text on a screen canvas (this is a new canvas that is in memory), then draw this canvas on your main canvas using your crop.

This will allow you to draw any part of your screensaver, for example, "crop" it to get the effect you need. This can be done using the usual drawImage method:

  ctx.drawImage([x: adjust for clipping], y, w, h, sourceCanvas, 0, 0, w, h); 

Of course, you will need to compress how many clips.

Hope this makes sense!

+1
source

Some notes:

1) If you want to copy the text to the end of the text, you can use the optional parameter maxWidth fillText () .

2) Another clipping method using globalCompositeOperation is presented here .

0
source

Source: https://habr.com/ru/post/944491/


All Articles