美文网首页
前端脚本实现canvas上写古诗

前端脚本实现canvas上写古诗

作者: 梦想成真213 | 来源:发表于2024-01-17 15:26 被阅读0次

    这两天开通了抖音账号,拍一些小孩子背诵古诗的视频,然后整理背过的古诗,把古诗内容和水墨画拼在一起,偶尔写点小脚本还是蛮有意思的,下面是代码:

    const { createCanvas, loadImage, registerFont } = require('canvas');
    const fs = require('fs');
    // 背景图路径
    const backgroundImagePath = `./src/bg/${Math.floor(Math.random() * 15)}.jpg`;
    // 字体路径
    const titleFontPath = './src/fonts/NotoSansSC-VariableFont_wght.ttf';
    const authorFontPath = titleFontPath;
    const poemFontPath = titleFontPath;
    
    // 读取古诗名和内容
    const argv = process.argv.slice(2)
    const fileText = fs.readFileSync(`./src/shi/${argv[0]}.txt`).toString()
    const content = fileText.split('\n')
    // 标题
    const title = content[0];
    // 作者
    const author = content[1];
    // 古诗内容
    const poem = content.slice(2).join('\n');
    console.log(title, `\n${author}`, `\n${poem}`)
    
    // 注册字体
    registerFont(titleFontPath, { family: 'NotoSansSC-SemiBold' });
    registerFont(authorFontPath, { family: 'NotoSansSC-ExtraBold' });
    registerFont(poemFontPath, { family: 'NotoSansSC-Black' });
    
    // 创建画布
    const canvas = createCanvas(800, 600);
    const ctx = canvas.getContext('2d');
    
    // 加载背景图
    loadImage(backgroundImagePath).then((image) => {
      // 绘制背景图
      ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
    
      // 设置标题样式
      ctx.font = '48px NotoSansSC-SemiBold';
      ctx.fillStyle = '#000000';
      ctx.textAlign = 'center';
    
      // 绘制标题
      ctx.fillText(title, canvas.width / 2, 100);
    
      // 设置作者样式
      ctx.font = '36px NotoSansSC-ExtraBold';
    
      // 绘制作者
      ctx.fillText(author, canvas.width / 2, 150);
    
      // 设置古诗样式
      ctx.font = '36px NotoSansSC-Bold';
      ctx.fillStyle = '#000';
      ctx.textAlign = 'left';
    
      // 计算古诗内容的行数和行高
      const poemLines = poem.split('\n');
      const lineHeight = 60;
      const totalHeight = poemLines.length * lineHeight;
      const poemStartY = (canvas.height - totalHeight) / 2;
    
      // 绘制古诗内容
      for (let i = 0; i < poemLines.length; i++) {
        const line = poemLines[i];
        const y = poemStartY + i * lineHeight;
        ctx.fillText(line, (canvas.width / 2) - 100, y + 50);
      }
    
      // 保存图片
      const outputImagePath = `./src/picture/${title}.jpg`;
      const stream = canvas.createJPEGStream();
      const out = fs.createWriteStream(outputImagePath);
      stream.pipe(out);
      out.on('finish', () => console.log('Image generated successfully.'));
    });
    

    实现逻辑就是:本地找个十几张水墨画,然后本地把古诗都写到 txt 文件中,随机给古诗找个背景图,生成古诗图片


    image.png

    相关文章

      网友评论

          本文标题:前端脚本实现canvas上写古诗

          本文链接:https://www.haomeiwen.com/subject/cmglodtx.html