Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

CSS3新要素 | 応用編 | transform:rotateで回転画像を作成

パンくず

CSS3新要素
応用編
transform:rotateで回転画像を作成

概要

要素の回転を行うtransform:rotateで回転する画像を作成します。

内容

JavaScriptのタイマーとCSS3のtransform:rotateを利用して画像を回転させます。

Point

VenderPrefix

現状、各社ブラウザごとにtransformの値を設定する属性がことなるため
動的にベンダープリフィックスを取得する必要があります。

function getVendorPrefix() {
  return (/webkit/i).test(navigator.appVersion) ? 'webkit' : (/firefox/i).test(navigator.userAgent) ? 'Moz' : 'opera' in window ? 'O' : '';
}
transform

JavaScriptでtransformを設定する場合

document.getElementById("対象id").style[ベンダープリフィックス + Transform'] = "rotate(角度deg)";

ベンダープリフィックスは

webkit系=webkit
FireFox=Moz
Opera=O

サンプル

<!DOCTYPE HTML>
<html lang="ja-JP">
  <head>
    <meta charset="UTF-8" />
    <title>transform:rotate</title>
    <style type="text/css">
    p {
      border-style:solclass;
      border-wclassth:1px;
      border-color:#000;
      background-color:gray;
      wclassth:200px;
      height:100px;
      padding-left:100px;
    }
p.container img {
  transform:rotate(0deg);
  -webkit-transform:rotate(0deg);
  -moz-transform:rotate(0deg);
  -ms-transform:rotate(0deg);
  -o-transform:rotate(0deg);
}
    </style>
    <script type="text/javascript">
    var deg=0;
    var timer;
    function rotate360deg() {
      if (deg > 360) {
        deg = 0;
      } else {
        deg+=10;
      }
      return deg;
    }
    
    function rollingImage(imgId) {
      timer = setInterval("rotateImage('" + imgId + "')",100);
    }
    
    function rotateImage(imgId) {
      document.getElementById(imgId).style[getVendorPrefix() + 'Transform'] = "rotate(" + rotate360deg() + "deg)";
    }
    
    function getVendorPrefix() {
      return (/webkit/i).test(navigator.appVersion) ? 'webkit' : (/firefox/i).test(navigator.userAgent) ? 'Moz' : 'opera' in window ? 'O' : '';
    }
    
    function unRollingImage(imgId) {
      clearInterval(timer);
    }
    
    </script>
  </head>
  <body>
  <p class="container"><img id="transform-rotate" class="transform-rotate" src="transform-rotate-rolling.png" style="" alt="" /></p>
  <input type="button" name="start" value="start" onclick="rollingImage('transform-rotate')" />
  <input type="button" name="stop" value="stop" onclick="unRollingImage('transform-rotate')" />
  </body>
</html>

完成画面のキャプチャ

※startを押すと回転します
開始前

回転中

関連

CSS3新要素 | 2D 3D 変形 | transform:rotate