前回のサイト制作では、CSSの’clip-path’を用い、要素を好きな形に切り抜いて、
それを並べるというものでしたが、今回ご紹介するものは、
JavaScriptの動きを加えたものです。
前回、今回は、imgタグを用いずに、’background-position’を用い、
要素の背景として画像をはめ込んでいます。
また、要素のサイズ調整はJavaScriptを用いて行い、どのような端末でも、
横幅に合わせて表示するようにしています。
CSSのクラスセレクタでは、’width’の初期値は親要素の幅に等しくなり、
‘height’はコンテンツに基づいて自動調整され、
コンテンツがない場合は0になります。
今回は、空の要素に画像を挿入するので、工夫が必要です。
HTML
<div class="scope">
<div class="target">
<div class="cover"></div>
</div>
</div>
CSS
.scope .target{
background-size: cover;
background-position: center center;
background-image:url("https://mf-ken.com/note/wp-content/uploads/2023/09/094ceaff0b4b0b117397b8db796ff564a60ca66b.png");
margin-right:auto;
margin-left:auto;
}
.scope .cover{
height:100%;
background-color:palegreen;
}
JavaScript
const scope = document.querySelector(".scope");
const target = scope.querySelector(".target");
const cover = target.querySelector(".cover");
let loaded = false;
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();
}
document.addEventListener("DOMContentLoaded",function(){
cover.style.display = "block";
/* 読み込まれた初期の状態では、画像を隠しておく */
loaded = true;
/* ロード完了より先にクリップパスが変更されないように制限 */
});
window.addEventListener("resize",ReSizing);
function ReSizing() {
const width = scope.offsetWidth;
const size = 0.75;
/* 親要素に対する、画像の縮尺比率 */
target.style.width = width * size + "px";
target.style.height = width * size * ratio + "px";
/* 縮小後、オリジナルの画像の縦横比に合わせる */
}
target.addEventListener("mouseout",Reset);
/* マウスアウトされると、初期状態に戻る */
target.addEventListener("mouseover", (event) => GetCoordinate(event));
target.addEventListener("mousemove", (event) => GetCoordinate(event));
/* マウスオーバーおよびマウスムーブで、関数を呼び出す */
function Reset(){
cover.style.display = "block";
target.style.clipPath = "none";
}
const diameter = 30;
function GetCoordinate(event) {
cover.style.display = "none";
/* coverを消す */
const bounding = target.getBoundingClientRect();
const height = bounding.height;
const width = bounding.width;
const x = event.clientX - bounding.left;
const y = event.clientY - bounding.top;
/* マウスの座標-要素の右上の座標 */
let coord_x = x / width * 100;
let coord_y = y / height * 100;
/* 100分率に変換 */
if(loaded){
target.style.clipPath = "circle(" + diameter + "% at " + coord_x +"% " + coord_y +"%)";
}
/* 最後に、クリップパスに変換 */
}