使用画布创建弧形文本

时间:2018-05-31 06:41:49

标签: javascript html canvas html5-canvas

有没有办法用画布创建弧形文本?我按照我们的回答:

How to make rooftext effect and valley text effect in HTML5 (or Fabric.js)

我得到的最好的东西是从屋顶或者底部的曲线。是否有任何在画布中创建弧?

2 个答案:

答案 0 :(得分:0)

body {
  background-color: #333;
  font-family: 'Luckiest Guy', cursive;
  font-size: 35px;
}

path {
  fill: transparent;
}

text {
  fill: #FF9800;
}
<svg viewBox="0 0 425 300">
  <path id="curve" d="M6,150C49.63,93,105.79,36.65,156.2,47.55,207.89,58.74,213,131.91,264,150c40.67,14.43,108.57-6.91,229-145" />
  <text x="25">
    <textPath xlink:href="#curve">
      Dangerous Curves Ahead
    </textPath>
  </text>
</svg>

答案 1 :(得分:0)

尝试将此文本设置为以圆弧形式显示。

&#13;
&#13;
function drawTextAlongArc(context, str, centerX, centerY, radius, angle) {
        var len = str.length, s;
        context.save();
        context.translate(centerX, centerY);
        context.rotate(-1 * angle / 2);
        context.rotate(-1 * (angle / len) / 2);
        for(var n = 0; n < len; n++) {
          context.rotate(angle / len);
          context.save();
          context.translate(0, -1 * radius);
          s = str[n];
          context.fillText(s, 0, 0);
          context.restore();
        }
        context.restore();
      }
      var canvas = document.getElementById('myCanvas'), 
        context = canvas.getContext('2d'),
        centerX = canvas.width / 2,
        centerY = canvas.height - 30,
        angle = Math.PI * 0.8,
        radius = 150;
      
      context.font = '30pt Calibri';
      context.textAlign = 'center';
      context.fillStyle = 'red';
      context.strokeStyle = 'blue';
      context.lineWidth = 4;
      drawTextAlongArc(context, 'Arc Canvas Text', centerX, centerY, radius, angle);

      // draw circle underneath text
      context.arc(centerX, centerY, radius - 10, 0, 2 * Math.PI, false);
      context.stroke();
&#13;
#canvas{
  display:block;
  margin:0 auto;
}
&#13;
<canvas id="myCanvas" width="578" height="250"></canvas>
&#13;
&#13;
&#13;