HTML5とjQueryでRotate|スクロールに応じて画像を回転させる方法 – How to rotate the image by scroll

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんにちは!今日は【HTML&jQueryでRotate スクロールに応じて画像を回転させる方法】について書きたいと思います。このところscroll連動系のサイトが多くなったのでちょっと作ってみました。個人的に直線的なパララックスサイトを作っといてなんですが回転の方が楽しいです。特定の位置で回転開始等も簡単にできていいですね。(追記:jQueryのみで画像回転を実装する方法も記事にしました。

Rotate v1 – DEMO

スクロールのタイミングでキャンバスに画像に回転を付けていくバージョンです。増加のみ。fillStyle,fillRect,clearRectで残像の調整も可能です。

HTML – 共通
<div id="scrollAll">
<h1><img id="logoR" src="images/rotate_t.png"></h1>
<canvas id="canvasBd" width="1210" height="1210"></canvas>
</div>
CSS – 共通

#scrollArea{height:8000px;}
#canvasBd{position:fixed; top:50%; left:50%; margin: -610px 0px 0px -610px;}
#logoR{position:fixed; top:50%; left:50%; margin: -35px 0px 0px -111px;}
JS
<script type="text/javascript">

var convas, ctx, R;
var Dig = 0;
var img = new Image();
img.src = "images/rotate.png";
function init() {
convas = document.getElementById("canvasBd");
ctx = convas.getContext("2d");
rotation();
}

function rotation() {
Dig = (Dig + 1) % 360;
ctx.fillStyle = ‘rgba(0, 0, 0, 0)’;
ctx.fillRect(0, 0, convas.width, convas.height);
ctx.clearRect(0, 0, convas.width, convas.height);
ctx.save();
ctx.translate(convas.width/2, convas.height/2);
R = Dig/180*Math.PI;
ctx.rotate(R);
ctx.translate(-img.width/2, -img.height/2);
ctx.drawImage(img, 0, 0);
ctx.restore();
}

$(function(){
init();
var windowH = $(‘#scrollArea’).innerHeight();
$(window).scroll(function(){
rotation();
var bodyH = $(window).height();
var scroll = Math.floor($(this).scrollTop());
var scrollAll = scroll + bodyH;
if( windowH <= scrollAll){
$(window).scrollTop(0,0);
}
});
});

</script>

Rotate v2 – DEMO

スクロールと同期した画像の回転バージョンです。scR = (windowH / 360) / Xの部分で何回転するかの指定をしています。こっちの方が現実的…かもしれませんね。(余談ですが、天体作ったら面白いかも)

JS

<script type="text/javascript">

var convas, ctx, R;

var img = new Image();
img.src = "images/rotate.png";

function init() {
convas = document.getElementById("canvasBd");
ctx = convas.getContext("2d");
rotation();
}

$(window).scroll(function(){
scrollAll = $(window).height() + $(this).scrollTop();
scR = (windowH / 360) / 4;
scRR = scrollAll / scR;
ctx.fillStyle = ‘rgba(0, 0, 0, 0)’;
ctx.fillRect(0, 0, convas.width, convas.height);
ctx.clearRect(0, 0, convas.width, convas.height);
ctx.save();
ctx.translate(convas.width/2, convas.height/2);
ctx.rotate(scRR/180*Math.PI);
ctx.translate(-img.width/2, -img.height/2);
ctx.drawImage(img, 0, 0);
ctx.restore();
if( windowH <= scrollAll){
$(window).scrollTop(0,0);
}
});

$(function(){
windowH = $(‘#scrollArea’).innerHeight();
init();
});

</script>

以上です!