Подсветка границ area с помощью canvas
Нужно чтобы на интерактивной карте при наведении на area подсвечивались её границы. Нашёл скрипт, основанный на canvas, который решает эту задачу.
Первоначально без особых проблем подстроил его под свои нужды, собственно для этого понадобилось только добавить в каждую area обработчики onmouseover='myHover(this);' onmouseout='myLeave();'. Но вчера обнаружил что выше моей карты(это модуль Joomla), вставили еще один модуль. То есть карта теперь расположена ниже. Естественно координаты ареа пришлось менять. И тут началось самое интересное: координаты area изменились, всплывающие подсказки, прикреплённые к area выводятся опять там где-нужно, а вот границы, продолжают отрисовываться где-то там где они были раньше, до того как изображение карты переместилось вниз. У меня, честно говоря, нет никаких догадок - откуда скрипт сейчас берёт координаты. Привожу целиком скрипт и html/css с которым он работает: <script> // stores the device context of the canvas we use to draw the outlines // initialized in myInit, used in myHover and myLeave var hdc; // shorthand func function byId(e){return document.getElementById(e);} // takes a string that contains coords eg - "227,307,261,309, 339,354, 328,371, 240,331" // draws a line from each co-ord pair to the next - assumes starting point needs to be repeated as ending point. function drawPoly(coOrdStr) { var mCoords = coOrdStr.split(',');//alert(mCoords); var i, n; n = mCoords.length; hdc.beginPath(); hdc.moveTo(mCoords[0], mCoords[1]); for (i=2; i<n; i+=2) { hdc.lineTo(mCoords[i], mCoords[i+1]); } hdc.lineTo(mCoords[0], mCoords[1]); hdc.stroke(); } function drawRect(coOrdStr) { var mCoords = coOrdStr.split(','); var top, left, bot, right; left = mCoords[0]; top = mCoords[1]; right = mCoords[2]; bot = mCoords[3]; hdc.strokeRect(left,top,right-left,bot-top); } function myHover(element) { var hoveredElement = element; var coordStr = element.getAttribute('coords'); var areaType = element.getAttribute('shape'); switch (areaType) { case 'polygon': case 'poly': drawPoly(coordStr); break; case 'rect': drawRect(coordStr); } } function myLeave() { var canvas = byId('myCanvas'); hdc.clearRect(0, 0, canvas.width, canvas.height); } function myInit() { // get the target image var img = byId('map_img'); var x,y, w,h; // get it's position and width+height x = img.offsetLeft; y = img.offsetTop; w = img.clientWidth; h = img.clientHeight; // move the canvas, so it's contained by the same parent as the image var imgParent = img.parentNode; var can = byId('myCanvas'); imgParent.appendChild(can); // place the canvas in front of the image can.style.zIndex = 1; // position it over the image can.style.left = x+'px'; can.style.top = y+'px'; // make same size as the image can.setAttribute('width', w+'px'); can.setAttribute('height', h+'px'); // get it's context hdc = can.getContext('2d'); // set the 'default' values for the colour/width of fill/stroke operations hdc.fillStyle = 'red'; hdc.strokeStyle = 'red'; hdc.lineWidth = 2; } </script> <script> window.onload = function() { myInit(); }; </script> <style> body { background-color: gray; } canvas { pointer-events: none; /* make the canvas transparent to the mouse - needed since canvas is position infront of image */ position: absolute; } </style> <canvas id='myCanvas'></canvas> <!-- gets re-positioned in myInit(); --> <img id="map_img" src="/maps/images/map.jpg" width="960" height="960" usemap="#Navigation"> <p><map name="Navigation" id="Navigation"> <area shape="poly" id="mapid0" onmouseover='myHover(this);' onmouseout='myLeave();' coords="521,477,500,472,495,410,522,406"> .... |
WalterScott,
<div style="position:relative"> <img id="map_img" src="/maps/images/map.jpg" width="960" height="960" usemap="#Navigation"> </div> |
Помогло, спасибо.
|
Часовой пояс GMT +3, время: 08:17. |