将文本调整为特定形状

Adjust text into specific shape

本文关键字:文本 调整      更新时间:2023-09-26

我有以下代码,我需要使用 JavaScript 来调整文本,使其适合圆圈。

这是当前代码:

#circle {
  background:blue;
  width:200px;
  height:200px;
  top: -100px;
  margin-top:50%;
  left: -100px;
  margin-left:50%;
  text-align:center;
  font-family:monospace; /* fixed size font, making it easy to implement */
  line-height:18px;
  font-size:18px;
  border-radius:100px;
}
<div id="circle">
  Hello World Helo World Helo World Helo World Helo World
</div>

默认情况下,文本将以正方形排列。如果找到适合圆的最大正方形,则可以调整填充以适应它。计算方法,适合圆的最大平方是这个公式:

((半径平方)/2)的平方根

((200 * 200)/2)的平方根;

(40000/2)的平方根;

(20000) 的平方根 = 141。

所以内容是 141px x 141px。由于您的圆圈在技术上是一个 200x200 的框,因此填充需要为 (200 - 141)/2 = 29.5px;

因此,您需要将其垂直居中。有许多"黑客"可以做到这一点。我正在使用以下许多之一。见 https://www.w3.org/Style/Examples/007/center.en.html

#circle {
  box-sizing:border-box;
  background:blue;
  width:200px;
  height:200px;
  text-align:center;
  font-family:monospace; /* fixed size font, making it easy to implement */
  line-height:18px;
  font-size:18px;
  border-radius:100px;
  padding:29px;
  position: relative
}
#circle p {
   box-sizing:border-box;
   width:141px;
   padding:0;
   margin: 0;
   position: absolute;               
   top: 50%;                         
   transform: translate(0, -50%) 
}   
<div id="circle">
  <p>Hello World Helo World Helo World Helo World Helo World</p>
</div>

如果您只想将文本放入圆圈中,只需将padding-top: 70px添加到#circle

见小提琴:https://jsfiddle.net/hzurmh8n/6/