仕事では、夏から本格的にJavaScriptの知識を鍛錬しています。
JavaScriptでは、計算・演算が出来る他、多様な条件・動作を付けて、
CSSを変更する事が出来ます。
前回では、CSSの’clip-path’プロパティを用い、
カーソルの座標に合わせて動かすというものでしたが、
今回はCSSの’transform’プロパティを使います。
値のrotateX(),rotateY()は、それぞれ、X軸、Y軸を回転軸に、
立体的に要素を回転させられます。
視覚的に立体感を出すには、親要素に’perspective’プロパティを用います。
‘perspective’とは視点を意味し、数字が大きくなるほど、
「遠くから」要素を見ている事になります。
作ったもの
↓
↓
↓
↓
↓
↓
↓
↓
↓
HTML
<div class="rotate-y">
<div class="back">
<div class="card"></div>
</div>
</div>
CSS
.rotate-y .back{
background-color:palegreen;
margin-right:auto;
margin-left:auto;
perspective:100vw;
}
.rotate-y .card{
background-size: cover;
background-position: center center;
background-image:url("https://mf-ken.com/note/wp-content/uploads/2023/09/094ceaff0b4b0b117397b8db796ff564a60ca66b.png");
height:100%;
}
JavaScript
const rotate_y = document.querySelector(".rotate-y");
const back = rotate_y.querySelector(".back");
const card = rotate_y.querySelector(".card");
const img = new Image();
img.src = "https://mf-ken.com/note/wp-content/uploads/2023/09/094ceaff0b4b0b117397b8db796ff564a60ca66b.png";
let ratio;
img.onload = function() {
ratio = img.height / img.width;
/* 画像の縦横比率 */
ReSizing();
}
let height;
let flag = false;
//アニメーションが一回しか行われないように制限
document.addEventListener("DOMContentLoaded",function(){
if(Detection(rotate_y)){
flag = true;
card.style.backgroundImage = 'url("https://mf-ken.com/note/wp-content/uploads/2023/09/b4ac7feb7f336e6a2b9b0f4efac8bd5d8a7fc401.png")';
card.style.transform = "rotateY(180deg)";
}
//もし、境界線以下にいる時、最初から画像を裏返しておく
});
window.addEventListener("resize",ReSizing);
function ReSizing(){
const width = rotate_y.offsetWidth;
const size = 0.6;
/* 親要素に対する、画像の縮尺比率 */
back.style.width = width * size + "px";
height = width * size * ratio;
back.style.height = height + "px";
/* 縮小後、オリジナルの画像の縦横比に合わせる */
}
function Detection(target){
const top = target.getBoundingClientRect().top;
return(top < 0);
/* 境界線を、要素の下側に設定 */
}
window.addEventListener("scroll",function(){
if(Detection(rotate_y) && !flag){
flag = true;
Reversible();
}
});
function Reversible(){
let deg = 0;
const animationInterval = setInterval(() => {
if(deg < 181){
if(deg == 90){
card.style.backgroundImage = 'url("https://mf-ken.com/note/wp-content/uploads/2023/09/b4ac7feb7f336e6a2b9b0f4efac8bd5d8a7fc401.png")';
}
/* 画像が裏返った所で、別の画像に差し替える */
/* ただし、縦横比が同一のもの */
card.style.transform = "rotateY(" + deg + "deg)";
deg++;
/* 1°=20ミリ秒のペースで回転 */
}else{
clearInterval(animationInterval);
/* 回転角度180°でイベント終了 */
}
}, 20);
}