반응 형 이미지 맵
반응 형 html 레이아웃에 기존 이미지 맵이 있습니다. 이미지는 브라우저 크기에 따라 크기가 조정되지만 이미지 좌표는 분명히 고정 된 픽셀 크기입니다. 이미지 맵 좌표의 크기를 조정하려면 어떤 옵션이 필요합니까?
반응 형 이미지 맵의 경우 플러그인을 사용해야합니다.
https://github.com/stowball/jQuery-rwdImageMaps (더 이상 유지되지 않음)
또는
https://github.com/davidjbradshaw/imagemap-resizer
주요 브라우저는 백분율 좌표를 올바르게 이해하지 못하며 모두 백분율 좌표를 픽셀 좌표로 해석합니다.
http://www.howtocreate.co.uk/tutorials/html/imagemaps
또한 브라우저가 구현하는지 테스트하기위한이 페이지
http://home.comcast.net/~urbanjost/IMG/resizeimg3.html
Matt Stow의 반응 형 이미지 맵 jQuery 플러그인
이미지 맵 대신 svg를 사용할 수도 있습니다. ;)
이를 수행하는 방법에 대한 학습서가 있습니다 .
- 다음은 멋진 호버 효과, 설명 및 링크가 포함 된 jsfiddle입니다. http://jsfiddle.net/eLbpmsaj/
.hover_group:hover {
opacity: 1;
}
#projectsvg {
position: relative;
width: 100%;
padding-bottom: 77%;
vertical-align: middle;
margin: 0;
overflow: hidden;
}
#projectsvg svg {
display: inline-block;
position: absolute;
top: 0;
left: 0;
}
<figure id="projectsvg">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1920 1080" preserveAspectRatio="xMinYMin meet" >
<!-- set your background image -->
<image width="1920" height="1080" xlink:href="http://placehold.it/1920x1080" />
<g class="hover_group" opacity="0">
<a xlink:href="https://example.com/link1.html">
<text x="652" y="706.9" font-size="20">First zone</text>
<rect x="572" y="324.1" opacity="0.2" fill="#FFFFFF" width="264.6" height="387.8"></rect>
</a>
</g>
<g class="hover_group" opacity="0">
<a xlink:href="https://example.com/link2.html">
<text x="1230.7" y="952" font-size="20">Second zone</text>
<rect x="1081.7" y="507" opacity="0.2" fill="#FFFFFF" width="390.2" height="450"></rect>
</a>
</g>
</svg>
</figure>
이미지 맵을 전혀 사용하지 않고 이미지 위에 절대적으로 위치하는 앵커 태그를 사용하는 솔루션을 가로 질러 실행했습니다. 유일한 단점은 핫스팟이 직사각형이어야한다는 것입니다. 그러나이 솔루션은 자바 스크립트에 의존하지 않고 CSS에만 의존한다는 것입니다. 앵커에 대한 HTML 코드를 생성하는 데 사용할 수있는 웹 사이트가 있습니다. http://www.zaneray.com/responsive-image-map/
이미지와 생성 된 앵커 태그를 상대적으로 배치 된 div 태그에 넣고 모든 것이 창 크기 조정 및 휴대 전화에서 완벽하게 작동했습니다.
David Bradshaw는이 문제를 해결하는 멋진 작은 라이브러리를 작성했습니다. jQuery를 사용하거나 사용하지 않고 사용할 수 있습니다.
여기에서 사용 가능합니다 : https://github.com/davidjbradshaw/imagemap-resizer
직사각형 적중 영역에 괜찮다면이 문제를 해결하는 비 JS 방법을 찾았습니다.
우선 이미지가 상대적으로 위치한 div에 있는지 확인하십시오. 그런 다음 이미지를이 div 안에 넣으십시오. 즉, div의 모든 공간을 차지합니다. 마지막으로 주 div 내에서 이미지 아래에 절대 위치 div를 추가하고 상단, 왼쪽, 너비 및 높이에 백분율을 사용하여 링크 적중 영역을 원하는 크기와 위치로 가져옵니다.
처음 작업 할 때 div에 검은 색 배경색 (이상적으로는 알파 페이딩이 있으므로 링크 된 내용을 볼 수 있음)을 제공하고 브라우저에서 코드 검사기를 사용하여 백분율을 실시간으로 조정하는 것이 가장 쉽다는 것을 알았습니다. 바로 사용할 수 있습니다.
작업 할 수있는 기본 개요는 다음과 같습니다. 백분율로 모든 작업을 수행하면 요소가 모두 이미지 배율과 동일한 상대 크기 및 위치를 유지하게됩니다.
<div style="position: relative;">
<img src="background-image.png" style="width: 100%; height: auto;">
<a href="/link1"><div style="position: absolute; left: 15%; top: 20%; width: 12%; height: 8%; background-color: rgba(0, 0, 0, .25);"></div></a>
<a href="/link2"><div style="position: absolute; left: 52%; top: 38%; width: 14%; height: 20%; background-color: rgba(0, 0, 0, .25);"></div></a>
</div>
Chrome 또는 선택한 브라우저에서 코드 관리자와 함께이 코드를 사용하고 상자가 제대로 표시 될 때까지 백분율을 조정하십시오 (소수 백분율을 더 정확하게 사용할 수 있음). 또한 선택 background-color
의를 transparent
당신이 당신의 히트 영역은 눈에 보이지 않는되고 싶어하기 때문에 그것을 사용할 준비가되면.
다음 방법은 완벽하게 작동하므로 여기에 전체 구현이 있습니다.
<img id="my_image" style="display: none;" src="my.png" width="924" height="330" border="0" usemap="#map" />
<map name="map" id="map">
<area shape="poly" coords="774,49,810,21,922,130,920,222,894,212,885,156,874,146" href="#mylink" />
<area shape="poly" coords="649,20,791,157,805,160,809,217,851,214,847,135,709,1,666,3" href="#myotherlink" />
</map>
<script>
$(function(){
var image_is_loaded = false;
$("#my_image").on('load',function() {
$(this).data('width', $(this).attr('width')).data('height', $(this).attr('height'));
$($(this).attr('usemap')+" area").each(function(){
$(this).data('coords', $(this).attr('coords'));
});
$(this).css('width', '100%').css('height','auto').show();
image_is_loaded = true;
$(window).trigger('resize');
});
function ratioCoords (coords, ratio) {
coord_arr = coords.split(",");
for(i=0; i < coord_arr.length; i++) {
coord_arr[i] = Math.round(ratio * coord_arr[i]);
}
return coord_arr.join(',');
}
$(window).on('resize', function(){
if (image_is_loaded) {
var img = $("#my_image");
var ratio = img.width()/img.data('width');
$(img.attr('usemap')+" area").each(function(){
console.log('1: '+$(this).attr('coords'));
$(this).attr('coords', ratioCoords($(this).data('coords'), ratio));
});
}
});
});
</script>
나를 위해 일하고 (코드에서 3 가지를 변경해야 함) :
previousWidth (원본 이미지 크기)
map_ID (이미지 맵의 ID)
img_ID (이미지의 ID)
HTML :
<div style="width:100%;">
<img id="img_ID" src="http://www.gravatar.com/avatar/0865e7bad648eab23c7d4a843144de48?s=128&d=identicon&r=PG" usemap="#map" border="0" width="100%" alt="" />
</div>
<map id="map_ID" name="map">
<area shape="poly" coords="48,10,80,10,65,42" href="javascript:;" alt="Bandcamp" title="Bandcamp" />
<area shape="poly" coords="30,50,62,50,46,82" href="javascript:;" alt="Facebook" title="Facebook" />
<area shape="poly" coords="66,50,98,50,82,82" href="javascript:;" alt="Soundcloud" title="Soundcloud" />
</map>
자바 스크립트 :
window.onload = function () {
var ImageMap = function (map, img) {
var n,
areas = map.getElementsByTagName('area'),
len = areas.length,
coords = [],
previousWidth = 128;
for (n = 0; n < len; n++) {
coords[n] = areas[n].coords.split(',');
}
this.resize = function () {
var n, m, clen,
x = img.offsetWidth / previousWidth;
for (n = 0; n < len; n++) {
clen = coords[n].length;
for (m = 0; m < clen; m++) {
coords[n][m] *= x;
}
areas[n].coords = coords[n].join(',');
}
previousWidth = img.offsetWidth;
return true;
};
window.onresize = this.resize;
},
imageMap = new ImageMap(document.getElementById('map_ID'), document.getElementById('img_ID'));
imageMap.resize();
return;
}
JSFiddle : http://jsfiddle.net/p7EyT/154/
아래 링크를 사용하여 반응 형 맵 이미지를 얻을 수 있습니다
window.onload = function () {
var ImageMap = function (map, img) {
var n,
areas = map.getElementsByTagName('area'),
len = areas.length,
coords = [],
previousWidth = 128;
for (n = 0; n < len; n++) {
coords[n] = areas[n].coords.split(',');
}
this.resize = function () {
var n, m, clen,
x = img.offsetWidth / previousWidth;
for (n = 0; n < len; n++) {
clen = coords[n].length;
for (m = 0; m < clen; m++) {
coords[n][m] *= x;
}
areas[n].coords = coords[n].join(',');
}
previousWidth = document.body.clientWidth;
return true;
};
window.onresize = this.resize;
},
imageMap = new ImageMap(document.getElementById('map_ID'), document.getElementById('img_ID'));
imageMap.resize();
return;
}
<div style="width:100%;">
<img id="img_ID" src="http://www.gravatar.com/avatar/0865e7bad648eab23c7d4a843144de48?s=128&d=identicon&r=PG" usemap="#map" border="0" width="100%" alt="" />
</div>
<map id="map_ID" name="map">
<area shape="poly" coords="48,10,80,10,65,42" href="javascript:;" alt="Bandcamp" title="Bandcamp" />
<area shape="poly" coords="30,50,62,50,46,82" href="javascript:;" alt="Facebook" title="Facebook" />
<area shape="poly" coords="66,50,98,50,82,82" href="javascript:;" alt="Soundcloud" title="Soundcloud" />
</map>
http://home.comcast.net/~urbanjost/semaphore.html 은 토론의 최상위 페이지이며 실제로 문제에 대한 JavaScript 기반 솔루션에 대한 링크가 있습니다. 나는 앞으로 HTML이 퍼센트 단위를 지원할 것이라는 통지를 받았지만 꽤 오랜 시간이 지났지 만 (지원이 나올 것이라고 들었을 때 아마 1 년이 지났을 것입니다) 그래서 해결책은 다음과 같습니다. JavaScript / ECMAScript에 익숙한 지 살펴볼 가치가 있습니다.
Github 에서 이미지 맵 플러그인을 확인하십시오 . 그것은 바닐라 JavaScript와 jQuery 플러그인으로 작동합니다.
$('img[usemap]').imageMap(); // jQuery
ImageMap('img[usemap]') // JavaScript
데모를 확인하십시오 .
나는 어떤 화면 크기로도 크기를 조정할 수있는 반응 형 이미지 맵을 표시하고 싶은 중요한 요구 사항을 발견 하고 중요한 것은 그 좌표를 강조하고 싶습니다 .
그래서 화면 크기와 이벤트에 따라 좌표의 크기를 조정할 수있는 많은 라이브러리를 시도했습니다. 그리고 거의 모든 브라우저에서 잘 작동하는 최고의 솔루션 (jquery.imagemapster.min.js)을 얻었습니다. 또한 이미지 맵을 만드는 Summer Plgin 과 통합했습니다 .
var resizeTime = 100;
var resizeDelay = 100;
$('img').mapster({
areas: [
{
key: 'tbl',
fillColor: 'ff0000',
staticState: true,
stroke: true
}
],
mapKey: 'state'
});
// Resize the map to fit within the boundaries provided
function resize(maxWidth, maxHeight) {
var image = $('img'),
imgWidth = image.width(),
imgHeight = image.height(),
newWidth = 0,
newHeight = 0;
if (imgWidth / maxWidth > imgHeight / maxHeight) {
newWidth = maxWidth;
} else {
newHeight = maxHeight;
}
image.mapster('resize', newWidth, newHeight, resizeTime);
}
function onWindowResize() {
var curWidth = $(window).width(),
curHeight = $(window).height(),
checking = false;
if (checking) {
return;
}
checking = true;
window.setTimeout(function () {
var newWidth = $(window).width(),
newHeight = $(window).height();
if (newWidth === curWidth &&
newHeight === curHeight) {
resize(newWidth, newHeight);
}
checking = false;
}, resizeDelay);
}
$(window).bind('resize', onWindowResize);
img[usemap] {
border: none;
height: auto;
max-width: 100%;
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-imagemapster@1.2.10/dist/jquery.imagemapster.min.js"></script>
<img src="https://discover.luxury/wp-content/uploads/2016/11/Cities-With-the-Most-Michelin-Star-Restaurants-1024x581.jpg" alt="" usemap="#map" />
<map name="map">
<area shape="poly" coords="777, 219, 707, 309, 750, 395, 847, 431, 916, 378, 923, 295, 870, 220" href="#" alt="poly" title="Polygon" data-maphilight='' state="tbl"/>
<area shape="circle" coords="548, 317, 72" href="#" alt="circle" title="Circle" data-maphilight='' state="tbl"/>
<area shape="rect" coords="182, 283, 398, 385" href="#" alt="rect" title="Rectangle" data-maphilight='' state="tbl"/>
</map>
누군가에게 도움을 바랍니다.
It depends, you can use jQuery to adjust the ranges proportionally I think. Why do you use an image map by the way? Can't you use scaling divs or other elements for it?
For those who don't want to resort to JavaScript, here's an image slicing example:
http://codepen.io/anon/pen/cbzrK
As you scale the window, the clown image will scale accordingly, and when it does, the nose of the clown remains hyperlinked.
Similar to Orland's answer here: https://stackoverflow.com/a/32870380/462781
Combined with Chris' code here: https://stackoverflow.com/a/12121309/462781
If the areas fit in a grid you can overlay the areas by transparent pictures using a width in % that keep their aspect ratio.
.wrapperspace {
width: 100%;
display: inline-block;
position: relative;
}
.mainspace {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
<div class="wrapperspace">
<img style="float: left;" title="" src="background-image.png" width="100%" />
<div class="mainspace">
<div>
<img src="space-top.png" style="margin-left:6%;width:15%;"/>
</div>
<div>
<a href="http://www.example.com"><img src="space-company.png" style="margin-left:6%;width:15%;"></a>
</div>
<div>
<a href="http://www.example.com"><img src="space-company.png" style="margin-left:6%;width:10%;"></a>
<a href="http://www.example.com"><img src="space-company.png" style="width:20%;"></a>
</div>
</div>
</div>
You can use a margin in %. Additionally "space" images can be placed next to each other inside a 3rd level div.
For some reason none of these solutions worked for me. I've had the best success using transforms.
transform: translateX(-5.8%) translateY(-5%) scale(0.884);
responsive width && height
window.onload = function () {
var ImageMap = function (map, img) {
var n,
areas = map.getElementsByTagName('area'),
len = areas.length,
coords = [],
imgWidth = img.naturalWidth,
imgHeight = img.naturalHeight;
for (n = 0; n < len; n++) {
coords[n] = areas[n].coords.split(',');
}
this.resize = function () {
var n, m, clen,
x = img.offsetWidth / imgWidth,
y = img.offsetHeight / imgHeight;
imgWidth = img.offsetWidth;
imgHeight = img.offsetHeight;
for (n = 0; n < len; n++) {
clen = coords[n].length;
for (m = 0; m < clen; m +=2) {
coords[n][m] *= x;
coords[n][m+1] *= y;
}
areas[n].coords = coords[n].join(',');
}
return true;
};
window.onresize = this.resize;
},
imageMap = new ImageMap(document.getElementById('map_region'), document.getElementById('prepay_region'));
imageMap.resize();
return;
}
참고URL : https://stackoverflow.com/questions/7844399/responsive-image-map
'programing tip' 카테고리의 다른 글
PHP에서 is_null ($ x) vs $ x === null (0) | 2020.07.02 |
---|---|
JAR 내에 JAR을 포함하는 클래스 경로 (0) | 2020.07.02 |
타입 힌트를 사용해 복수의 리턴 타입을 지정하는 방법 (0) | 2020.07.02 |
MySql에서 아포스트로피 ( ')를 피하는 방법? (0) | 2020.07.02 |
Gulp.js 작업, src로 돌아 갑니까? (0) | 2020.07.02 |