Text

 

We can draw text or outlined (stroke) text on a canvas using the code below:

ctx.fillStyle = "red";
ctx.font = "100px Times Roman";
ctx.fillText("Some Text", 10, 150);

ctx.strokeStyle = "blue";
ctx.font = "50px Arial";
ctx.lineWidth = 3;
ctx.strokeText("Some Text Outline", 10, 350);

 

Example of text on a canvas (Run Example)

<!-- Author: Derek O Reilly, Dundalk Institute of Technology, Ireland. -->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>GENIUS worked example</title>
        <link rel="shortcut icon" type="image/png" href="images/genius_icon.png"/>
        <style>
            #gameCanvas
            {
                /* the canvas styling usually does not change */
                outline:1px solid darkgrey;
                width:500px;
                height:500px;
            }
        </style>
    </head>

    <body>
        <canvas id = "gameCanvas"></canvas>

        <script>
            let canvas = document.getElementById("gameCanvas");
            canvas.width = canvas.clientWidth;
            canvas.height = canvas.clientHeight;
            let ctx = canvas.getContext("2d");

            // draw text on a canvas
            ctx.fillStyle = "red";
            ctx.font = "100px Times Roman";
            ctx.fillText("Some Text", 10, 150);

            ctx.strokeStyle = "blue";
            ctx.font = "50px Arial";
            ctx.lineWidth = 3;
            ctx.strokeText("Some Text Outline", 10, 350);
        </script>
    </body>
</html>

Write code to dislay a message with an outline, as shown here.

Items will be draw on the canvas in the order that they are listed in the code. Any drawing outside of a canvas's logical area will be clipped.

Example of clipped text on a canvas (Run Example)

<!-- Author: Derek O Reilly, Dundalk Institute of Technology, Ireland. -->

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>GENIUS worked example</title>
        <link rel="shortcut icon" type="image/png" href="images/genius_icon.png"/>
        <style>
            #gameCanvas
            {
                /* the canvas styling usually does not change */
                outline:1px solid darkgrey;
                width:500px;
                height:500px;
            }
        </style>
    </head>

    <body>
        <canvas id = "gameCanvas"></canvas>

        <script>
            let canvas = document.getElementById("gameCanvas");
            canvas.width = canvas.clientWidth;
            canvas.height = canvas.clientHeight;
            let ctx = canvas.getContext("2d");

            // draw some text on the canvas
            ctx.fillStyle = "red";
            ctx.font = "120px Times Roman";
            ctx.fillText("Clipped Text", 10, 150);
        </script> 
    </body>
</html>