UniquePineapple UniquePineapple - 3 months ago 8
Javascript Question

Draw upper half of a string in Javascript

If I have a string, such as

"Hello World!"
How would I draw only the upper half of said string to a javascript canvas?


I would want it to appear like
this.

Answer

using the .clip() method, you can specify a section of the canvas in which to draw with anything outside the clipping region being omitted; a la:

<html>
<body style="background:black;">
<canvas id="myCanvas" width="300" height="200"></canvas>
</body>
<script>

    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    // Clip a rectangular area
    ctx.rect(50,20,200,80);
    //ctx.stroke();
    ctx.clip();
    // Draw text into clip()
    ctx.fillStyle="#666666";
    ctx.font = "30px Arial";
    ctx.fillText("Hello World",60,110);

</script>
</html>

see this entry for details

good luck!

Comments