LoginSignup
1

More than 3 years have passed since last update.

続編:Javascriptでテキストを自動で円形にする

Posted at

はじめに

この記事は別記事「HTMLとCSSで魔法陣を描いてみる」の続編です。続編みたいなものです。

自動化したので、長いテキストでも円形にできるようになった。

サンプル

See the Pen OJVmLOd by Yomogenium (@yomogenium) on CodePen.

コード

html

<style>
/* cssはなくても大丈夫だが、つけないとほぼ確実に見た目が悪くなる。 */
#test{
  background-color: black;
  color: white;
  position: relative;
  width: 400px;
  height: 400px;
}
</style>

<div id="test">I am the flesh and bone of my own sword, Steel flows through my body, And fire is what courses through my blood, I have created over thousand blades. Unknown to Death. Nor known to life, Many times have withstood enormous pain to create thousands of weapons. And yet those hands that are brave so much never hold anything, So as I pray now I call for “Unlimited blade works”.</div>

<script type="text/javascript">
(function(){

function ToArch(element){


  // 要素内のテキストを抜き出して配列にする
  var text = element.textContent;
  text = text.split('');

  // 要素内のテキストを1文字ずつかこみ、それらに角度と高さを設定
  element.innerHTML = '';
  for(var int = 0; int < text.length; int++){

    var divnode = null;

    // 要素の角度
    var divrotate = (360 / text.length) * int;

    divnode = document.createElement('span');
    divnode.innerHTML = text[int];
    divnode.style.position = 'absolute';
    divnode.style.height = '50%';
    divnode.style.color = 'unset';
    divnode.style.transformOrigin = 'bottom center';
    divnode.style.top = '0';
    divnode.style.bottom = '0';
    divnode.style.left = '49.5%';
    divnode.style.transform = 'rotate(' + divrotate + 'deg)';
    element.appendChild(divnode);
  }
  return element;
}

// 引数にはdocument要素を入れること。
var archtarget = document.getElementById('test');
ToArch(archtarget);
})();
</script>

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1