使用canvas生成一张名片

在前端开发中,使用HTML5的<canvas>元素可以动态地生成图像。以下是一个简单的示例,展示如何使用<canvas>来生成一张名片:

  1. HTML结构
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>名片生成器</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="businessCard" width="600" height="400"></canvas>
    <script src="script.js"></script>
</body>
</html>
  1. JavaScript代码 (script.js文件):
window.onload = function() {
    const canvas = document.getElementById('businessCard');
    const ctx = canvas.getContext('2d');

    // 设置背景颜色
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 添加边框
    ctx.strokeStyle = '#000';
    ctx.strokeRect(0, 0, canvas.width, canvas.height);

    // 添加姓名
    ctx.font = '30px Arial';
    ctx.fillStyle = '#333';
    ctx.textAlign = 'center';
    ctx.fillText('张三', canvas.width / 2, 60);

    // 添加职位
    ctx.font = '20px Arial';
    ctx.fillText('前端开发工程师', canvas.width / 2, 100);

    // 添加公司信息
    ctx.font = '18px Arial';
    ctx.fillText('XXX科技有限公司', canvas.width / 2, 140);

    // 添加联系方式
    ctx.font = '16px Arial';
    ctx.fillText('电话: 123-456-7890', 50, 200);
    ctx.fillText('邮箱: zhangsan@example.com', 50, 225);

    // 添加Logo (假设你有一个logo.png图片)
    const image = new Image();
    image.src = 'logo.png'; // 确保此路径指向有效的图像文件
    image.onload = function() {
        ctx.drawImage(image, canvas.width - 100, 10, 80, 80); // 在右上角绘制Logo
    };
};

这个示例创建了一个简单的名片,包括姓名、职位、公司信息、联系方式和一个Logo。你可以根据需要调整文本内容、字体、颜色、位置等。同时,确保logo.png的路径是有效的,或者替换为你自己的Logo图像。

posted @   王铁柱6  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示