JS skills – drawing special characters in canvas

Time:2021-6-10

The simplest and most practical way to draw special symbols in canvas is to usecharacter, withfillTextTo draw in the same way. Of course, if there are special requirements for the style of special symbols, the use of pictures is also a good choice. Here we only introduce the character drawing method.

Scheme 1: use special characters directly in the code

Taking win10 system as an example, in the process of code input (switching to Chinese), you can click the smiley face icon behind the candidate words to open the special character selection panel

JS skills - drawing special characters in canvas

Select the special characters you need in the pop-up panel to automatically type them into the code
JS skills - drawing special characters in canvas

Take “infinite symbol” as an example:

code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    < title > HTML5 canvas drawing special characters
    <style type="text/css">
    canvas {
        border: 1px solid #ccc;
    }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="500" height="500"></canvas>
    <script type="text/javascript">
    //Get canvas.context
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    
    //Text style
    context.fillStyle = '#1ABFFF';
    Context. Font ='120px "Microsoft YaHei ';
    
    //Draw text
    context.fillText('∞', 200, 200);
    </script>
</body>

</html>

Scheme 2: use Unicode code

Query the Unicode code of the required special characters, for example, the Unicode code of “infinite symbol” is\u221e, defined in code as'\\u221e', and then useevalFunction to parse, note that when parsing, Unicode code must add a layer of quotation marks outside.

Unicode code conversion – Webmaster tool

code

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    < title > HTML5 canvas drawing special characters
    <style type="text/css">
    canvas {
        border: 1px solid #ccc;
    }
    </style>
</head>

<body>
    <canvas id="myCanvas" width="500" height="500"></canvas>
    <script type="text/javascript">
    //Get canvas.context
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    
    //Text style
    context.fillStyle = '#1ABFFF';
    Context. Font ='120px "Microsoft YaHei ';

    //Draw text
    var infinCode = "\u221e";
    context.fillText(eval('"' + infinCode + '"'), 200, 200);
    </script>
</body>

</html>

The final effect

JS skills - drawing special characters in canvas