美文网首页
canvas 文字 绘制

canvas 文字 绘制

作者: 暴躁程序员 | 来源:发表于2024-12-15 11:27 被阅读0次
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>canvas 文字 绘制</title>
    <style>
      #canvas {
        background-color: #f9f9f9;
      }
    </style>
  </head>

  <body>
    <canvas id="canvas">浏览器不支持 canvas </canvas>
  </body>
  <script>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.height = 500;
    canvas.width = 500;

    // 填充文字:大小字体、对齐方式、文字颜色
    ctx.font = "24px STHeiti, SimHei";
    ctx.textAlign = "left"; // left center right
    ctx.fillStyle = 'orange'; // left center right
    ctx.fillText("云想衣裳花想容 春风拂槛露华浓", 0, 24, 100); // 填充文本:ctx.fillText(text, x, y, maxWidth);

    // 文本超出换行
    function wrapText(context, text, x, y, maxWidth, lineHeight) {
      var words = text.split(" ");
      var line = "";

      for (var n = 0; n < words.length; n++) {
        var testLine = line + words[n] + " ";
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
          context.fillText(line, x, y);
          line = words[n] + " ";
          y += lineHeight;
        } else {
          line = testLine;
        }
      }
      context.fillText(line, x, y);
    }
    wrapText(ctx, "云想衣裳花想容 春风拂槛露华浓", 0, 100, 100, 26);

    // 描边文字:大小字体、对齐方式、文字颜色
    ctx.font = "38px STHeiti, SimHei";
    ctx.textAlign = "left"; // left center right
    ctx.strokeStyle = 'orange'; // left center right
    ctx.strokeText("云想衣裳花想容 春风拂槛露华浓", 0, 240, 500); // 描边文本:ctx.strokeText(text, x, y, maxWidth);
  </script>
</html>

相关文章

网友评论

      本文标题:canvas 文字 绘制

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