使用HTML5绘制一个经典“旺仔”的头像

104 阅读1分钟

"HTML5提供了丰富的绘图功能,我们可以使用canvas元素来绘制图形和图像。下面是一个使用HTML5绘制经典“旺仔”头像的示例代码:

<!DOCTYPE html>
<html>
<head>
    <title>绘制“旺仔”头像</title>
    <style>
        canvas {
            background-color: #f1f1f1;
        }
    </style>
</head>
<body>
    <canvas id=\"avatar\" width=\"200\" height=\"200\"></canvas>

    <script>
        // 获取canvas元素
        var canvas = document.getElementById(\"avatar\");
        var ctx = canvas.getContext(\"2d\");

        // 绘制头部
        ctx.beginPath();
        ctx.arc(100, 100, 80, 0, 2 * Math.PI);
        ctx.fillStyle = \"#ffdb00\";
        ctx.fill();
        ctx.lineWidth = 2;
        ctx.strokeStyle = \"#000000\";
        ctx.stroke();

        // 绘制眼睛
        ctx.beginPath();
        ctx.arc(70, 80, 15, 0, 2 * Math.PI);
        ctx.fillStyle = \"#ffffff\";
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.arc(130, 80, 15, 0, 2 * Math.PI);
        ctx.fillStyle = \"#ffffff\";
        ctx.fill();
        ctx.stroke();

        // 绘制嘴巴
        ctx.beginPath();
        ctx.arc(100, 130, 40, Math.PI / 6, 5 * Math.PI / 6);
        ctx.lineWidth = 8;
        ctx.strokeStyle = \"#000000\";
        ctx.stroke();

        // 绘制鼻子
        ctx.beginPath();
        ctx.moveTo(100, 95);
        ctx.lineTo(85, 115);
        ctx.lineTo(115, 115);
        ctx.closePath();
        ctx.fillStyle = \"#ffdb00\";
        ctx.fill();
        ctx.stroke();

        // 绘制眉毛
        ctx.beginPath();
        ctx.moveTo(55, 60);
        ctx.lineTo(85, 70);
        ctx.moveTo(145, 70);
        ctx.lineTo(175, 60);
        ctx.lineWidth = 4;
        ctx.stroke();

        // 绘制字体
        ctx.font = \"20px Arial\";
        ctx.fillStyle = \"#000000\";
        ctx.fillText(\"旺仔\", 80, 180);
    </script>
</body>
</html>

以上代码通过canvas元素和getContext方法获取绘图上下文,然后使用绘图上下文的方法来绘制各个部分,最后实现了一个经典的“旺仔”头像。"