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" /> <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(); } }); </script> </head> <body> <canvas id="canvas" width=300 height=300></canvas> </body> </html>
markE source share