本案例为后端课程中的前端内容,使用了HTML,CSS,JavaScript技术。

在绘制时使用了Canvas画布来实现对应效果。

可以改进的地方有爱心的绘制,在绘制时显示绘制路线。

成果展示

  • 绘制爱心:

  • 显示"I love you" :

  • 显示“我喜欢你” :

相关代码

  • page.html:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表白页面</title>
    <link rel="stylesheet" href="styles.css">
</head>
 
<body>
    <h1>表白页面</h1>
    <div class="buttons">
        <button onclick="drawHeart()">绘制爱心</button>
        <button onclick="showMessage('I love you! — from Name')">显示“I love you!”</button>
        <button onclick="showMessage('我喜欢你 —— 姓名')">显示“我喜欢你”</button>
    </div>
    <canvas id="myCanvas"></canvas>
</body>
 
<script>
    const canvas = document.getElementById("myCanvas");
        const ctx = canvas.getContext("2d");
 
        // 设置canvas宽高
        canvas.width = 400;
        canvas.height = 400;
 
        // 清空画布
        function clearCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
        }
 
        // 绘制爱心
        function drawHeart() {
            clearCanvas();
 
            ctx.fillStyle = "#ed7e7e";
            ctx.beginPath();
 
            // 使用公式绘制爱心,进行适当的缩放和移动到画布中央
            let scale = 10; // 缩放因子
            let offsetX = canvas.width / 2; // x轴平移
            let offsetY = canvas.height / 2; // y轴平移
 
            ctx.moveTo(offsetX, offsetY);
 
            for (let t = 0; t <= Math.PI * 2; t += 0.01) {
                let x = 16 * Math.pow(Math.sin(t), 3);
                let y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);
 
                // 将公式的x和y坐标进行缩放和平移,使其位于画布中央
                ctx.lineTo(offsetX + x * scale, offsetY - y * scale);
            }
 
            ctx.closePath();
            ctx.fill();
        }
 
        // 显示消息
        function showMessage(message) {
            clearCanvas();
            ctx.font = "30px Arial";
            ctx.fillStyle = "black";
            ctx.textAlign = "center";
            ctx.fillText(message, canvas.width / 2, canvas.height / 2);
        }
 
</script>
 
</html>
  • styles.css:

body {
    text-align: center;
    font-family: Arial, sans-serif;
    background-color: #f9f9f9;
}
 
h1 {
    color: #ef9c9c;
    margin-top: 20px;
}
 
.buttons {
    margin-bottom: 20px;
}
 
button {
    padding: 10px 20px;
    font-size: 16px;
    margin: 5px;
    cursor: pointer;
    background-color: #ef9c9c;
    color: white;
    border: none;
    border-radius: 5px;
}
 
button:hover {
    background-color: #ec7070;
}
 
canvas {
    border: 1px solid #d3d3d3;
    margin-top: 20px;
    background-color: #fff3f3;
}

一个老鼠人