このページでは、HTMLのクリッカブルマップをJavaScriptでレスポンシブ対応する方法を紹介しています。
画像サイズの変化に合わせてクリック領域(<area>タグのcoords)を自動調整するクラスを自作。
jQueryやSVGを使わず、純粋なJavaScriptで軽量に実現しています。
コピペで導入できるので、既存のサイトにも簡単に組み込めます。
■使い方
クリッカブルマップはとても便利なのですが、レスポンシブに対応していないので困ります。
しかし以下のJavascriptを<head></head>のタグ内にコピペで入れるだけで、クリッカブルマップがレスポンシブ対応になります。
<script>
class TMamResponsive{
constructor(){
this.alloc=[];
let imgs=document.querySelectorAll("img");
let maps=document.querySelectorAll("map");
for(let i=0;i<imgs.length;i++){
let usemap=imgs[i].getAttribute("usemap");
if(usemap!==null){
usemap=usemap.replace('#','');
for(let j=0;j<maps.length;j++){
let name=maps[j].getAttribute("name");
if(name!==null){
//img.usemapとmap.nameが等しい場合
if(usemap==name){
if(maps[j].children.length>0){
let l=this.alloc.length;
this.alloc[l]=[];
this.alloc[l].img=imgs[i];
this.alloc[l].nw=imgs[i].naturalWidth;
this.alloc[l].maps=[];
let areanum=0;
for(let k=0;k<maps[j].children.length;k++){
if(maps[j].children[k].tagName=='AREA'){
this.alloc[l].maps[areanum]=[];
this.alloc[l].maps[areanum].area=maps[j].children[k];
this.alloc[l].maps[areanum].coords=this.alloc[l].maps[areanum].area.getAttribute("coords");
areanum++;
}
}
break;
}
}
}
}
}
}
window.addEventListener('resize',function(){
this.resize();
}.bind(this));
this.resize();
}
resize(){
for(let i=0;i<this.alloc.length;i++){
let style=window.getComputedStyle(this.alloc[i].img);
let w=parseInt(style.width);
for(let j=0;j<this.alloc[i].maps.length;j++){
let v=this.alloc[i].maps[j].coords.split(',');
for(let k=0;k<v.length;k++){
v[k]=v[k]*w/this.alloc[i].nw;
}
let c=v.join(',');
this.alloc[i].maps[j].area.setAttribute("coords",c);
}
}
}
}
window.addEventListener('load',function(){
MamResponsive=new TMamResponsive;
});
</script>
■使用例
ブラウザの幅を狭くしたり広くしたりしてもクリッカブルマップのクリック領域はレスポンシブに対応しています。
<img src="./imgs/js_clickable_map_responsive.png" usemap="#imgmap" style="max-width:100%;" />
<map name="imgmap">
<area shape="poly" coords="36,120, 98,106, 126,44, 154,108, 218,120, 176,172, 184,224, 126,218, 70,246, 76,174" href="javascript:alert('星をクリック');">
<area shape="rect" coords="300,60, 466,246" href="javascript:alert('正方形をクリック');">
<area shape="circle" coords="648,158, 94" href="javascript:alert('円をクリック');">
<!-- <area shape="default" href="javascript:alert('図形以外をクリック');"> -->
</map>
