使用HTML5绘制一只卡通版米老鼠

85 阅读1分钟

"```markdown

使用HTML5绘制一只卡通版米老鼠

在这篇文章中,我们将使用HTML5的Canvas API绘制一只卡通版米老鼠。通过简单的几何形状和颜色填充,我们可以创建出可爱的米老鼠图像。

<!DOCTYPE html>
<html lang=\"zh\">
<head>
    <meta charset=\"UTF-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>米老鼠绘制</title>
    <style>
        canvas {
            border: 1px solid #000;
            display: block;
            margin: 20px auto;
        }
    </style>
</head>
<body>
    <canvas id=\"mickey\" width=\"400\" height=\"400\"></canvas>
    <script>
        const canvas = document.getElementById('mickey');
        const ctx = canvas.getContext('2d');

        // 绘制米老鼠的头部
        function drawHead() {
            ctx.beginPath();
            ctx.arc(200, 200, 100, 0, Math.PI * 2, true); // 头部
            ctx.fillStyle = '#000'; // 黑色
            ctx.fill();
            ctx.closePath();
        }

        // 绘制米老鼠的耳朵
        function drawEars() {
            ctx.beginPath();
            ctx.arc(120, 120, 50, 0, Math.PI * 2, true); // 左耳朵
            ctx.fill();
            ctx.closePath();

            ctx.beginPath();
            ctx.arc(280, 120, 50, 0, Math.PI * 2, true); // 右耳朵
            ctx.fill();
            ctx.closePath();
        }

        // 绘制米老鼠的眼睛
        function drawEyes() {
            ctx.beginPath();
            ctx.arc(170, 180, 15, 0, Math.PI * 2, true); // 左眼
            ctx.fillStyle = '#fff'; // 白色
            ctx.fill();
            ctx.closePath();

            ctx.beginPath();
            ctx.arc(230, 180, 15, 0, Math.PI * 2, true); // 右眼
            ctx.fill();
            ctx.closePath();

            ctx.beginPath();
            ctx.arc(170, 180, 7, 0, Math.PI * 2, true); // 左眼球
            ctx.fillStyle = '#000'; // 黑色
            ctx.fill();
            ctx.closePath();

            ctx.beginPath();
            ctx.arc(230, 180, 7, 0, Math.PI * 2, true); // 右眼球
            ctx.fill();
            ctx.fillStyle = '#000'; // 黑色
            ctx.fill();
            ctx.closePath();
        }

        // 绘制米老鼠的鼻子
        function drawNose() {
            ctx.beginPath();
            ctx.ellipse(200, 220, 20, 10, 0, 0, Math.PI * 2); // 鼻子
            ctx.fillStyle = '#000'; // 黑色
            ctx.fill();
            ctx.closePath();
        }

        // 绘制米老鼠的嘴巴
        function drawMouth() {
            ctx.beginPath();
            ctx.arc(200, 240, 30, 0, Math.PI, false); // 嘴巴
            ctx.strokeStyle = '#000'; // 黑色
            ctx.lineWidth = 5;
            ctx.stroke();
            ctx.closePath();
        }

        // 组合绘制
        function drawMickey() {
            drawHead();
            drawEars();
            drawEyes();
            drawNose();
            drawMouth();
        }

        drawMickey();
    </script>
</body>
</html>

以上代码创建了一个400x400像素的Canvas,并使用JavaScript绘制了卡通版米老鼠。通过arcellipse方法,我们可以绘制出米老鼠的头部、耳朵、眼睛、鼻子和嘴巴。每个部分都使用了不同的填充颜色,以展示米老鼠的可爱形象。运行代码后,可以看到一只简单的卡通米老鼠。