2013-10-02 36 views
3

我正試圖弄清楚這樣做的最佳方式。定義一個圖像上的多個點擊區域

基本上我有一個圖像是美國的地圖,我希望能夠爲每個州定義點擊區域。 (所以他們必須是奇形)

我已經做了一些關於在html5畫布和JavaScript中定義命中區域的研究。雖然我還沒有找到太多的創建奇怪的形狀區域..

這是最好的方式去呢?你們是否有其他建議?

我也希望能夠突出顯示個別區域,一旦鼠標在它上面,並根據點擊次序改變顏色,所以定義的區域必須相當準確。

最好是將每個狀態分成不同的圖像,然後在主容器中使用絕對定位?

+0

嘗試尋找到D3和GeoJSON的圖。您可以爲d3生成的每個svg對象分配點擊偵聽器。 – 0xcaff

+0

這是專門針對美國地圖嗎,還是會出現其他圖像?我很確定有一個jQuery地圖插件可以做到這一點。\ – tymeJV

+0

是的,這裏是:http://jvectormap.com/ – tymeJV

回答

5

你可以使用一個<map>這樣的:

<img src="yourImage.gif" width="99" height="99" alt="YourImage" usemap="#YourMap"> 
//The usemap attribute must match the name attribute of your map. 
<map name="YourMap"> 
    <area shape="rect" coords="0,0,82,126" href="path1.htm" alt="Path1"> 
    //Coords are x, y of the top left corner and the bottom right corner of the rectangle 
    <area shape="circle" coords="90,58,3" href="path2.htm" alt="Path2"> 
    //Coords are the x, y of the center of the circle and the lenght of half the diameter of the circle 
    <area shape="poly" coords="124,58,8, 1" href="path3.htm" alt="Path3"> 
    //Coords are the x, y of each points in the shape drew for an pentagone (5 corners) 
    //The coords attribute could look like this coords="0, 0, 10, 10, 5, 10, 10, 5, 12, 13" 
    //I know this dont make a pentagone but it does ilustrate that you need 5 pairs of  
    //numbre in the coords and that if you need more of them you can add however you need . 
</map> 

然後在區域標籤的href屬性,你可以把自己的路徑在用戶進入時,他點擊的區域。

+0

好帥哥!這看起來很完美。謝謝! – n388mm

+2

@ n388mm請標記爲解決方案,謝謝! –

1

創建圖像的可選部分並非易事,這些部分完全對準地圖,因此我們可以使用d3,SVG和geojson將美國繪製爲svg。

var width = 1000, // create constants for svg width and height 
    height = 500, 
    projection = d3.geo.albersUsa(); //get projection 
// albersusa is a special projection for the united states 
var svg = d3.select("body") //select the body and create the svg with the width and height constants. 
    .append("svg") 
    .attr({ 
    width:width, 
    height:height 
    }); 

var g = svg.append("g"); // append a svg group for the map 

d3.json("geo.json", function(data){ //fetch the json data 
    console.log(data.features); 
    g.selectAll("path") //draw the map 
    .data(data.features) 
    .enter() 
     .append("path") 
     .attr("d", d3.geo.path().projection(projection)) 
     .on("click", function(d){ // add onclick listener that logs the state clicked on. 
     console.log("You clicked on " + d.properties.NAME, d); 
     }); 
});  

在圖像上使用SVG的優點是,svg元素可以使用CSS3轉換動畫,也可以使用JavaScript進行操作。 我在我的google drive上託管了一個這樣的例子。打開控制檯並開始點擊狀態。

+0

這太棒了!我不知道你可以使用svg和geojson。 (顯示有更多的學習)大聲笑 謝謝老兄! – n388mm

+1

[d3主頁是學習d3的好地方。](http://d3js.org/) – 0xcaff

相關問題