3

我正在尝试找出最好的方法来做到这一点。

基本上我有一个图像是美国的地图,我希望能够为每个州定义一个点击区域。(所以它们必须是奇怪的形状)

我已经做了一些关于在 html5 画布和 javascript 中定义命中区域的研究。虽然我在创建奇怪形状的区域方面没有找到太多东西..

这是最好的方法吗?大家还有什么建议吗?

我还希望能够在鼠标悬停后突出显示单个区域并让它根据点击顺序更改颜色,因此定义的区域必须相当准确。

最好将每个状态拆分为不同的图像,然后在主容器内使用绝对定位?

4

3 回答 3

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>

然后在 area 标签的 href 属性中,您可以将自己的路径放置到用户单击该区域时所去的位置。

于 2013-10-02T14:49:58.703 回答
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 进行操作。我在我的谷歌驱动器上托管了一个这样的例子。打开控制台并开始单击状态。

于 2013-10-02T16:06:17.940 回答
0

相当多的 JavaScript 画布库可以帮助您解决这类问题,例如 Raphael ( http://raphaeljs.com/world/ ) 或 KineticJS ( http://www.html5canvastutorials.com/labs/html5- canvas-world-map-svg-path-with-kineticjs/

于 2013-10-18T17:04:19.513 回答