基于<area />坐标的Color <canvas>

时间:2015-11-15 13:11:45

标签: jquery html5

当我将鼠标悬停在图像中的区域元素上时,我试图填充多边形,但我无法弄清楚如何在区域坐标和画布坐标之间进行坐标转换。

HTML看起来像这样:

<div style="width:80%;margin:auto;">
    <img id="MyImg" src="http://www.publicdomainpictures.net/pictures/80000/nahled/3d-shape-icons.jpg" usemap="#Map" style="overflow:hidden;" />
    <canvas id="map_canvas" style="z-index: 10; pointer-events: none;"></canvas>
    <map name="Map" id="MyMap">
        <area alt="" title="" href="#" shape="poly" coords="20,7,12,22,19,49,19,76,13,92,17,110,41,118,67,112,101,118,132,109,131,86,124,61,130,36,132,13,109,4,77,13,58,10,37,2,28,3,15,14" />
        <area alt="" title="" href="#" shape="poly" coords="184,17,181,33,185,52,174,62,165,82,178,95,200,99,208,115,219,126,245,116,254,99,267,98,286,90,289,66,272,53,270,33,271,16,258,8,238,13,234,21,227,19,208,9,193,12" />
        <area alt="" title="" href="#" shape="poly" coords="349,8,333,18,322,44,316,62,327,88,342,111,364,121,402,121,427,106,437,81,442,60,439,40,424,11,395,2,366,2" />
        <area alt="" title="" href="#" shape="poly" coords="501,7,479,34,470,49,472,78,480,103,527,128,577,107,589,48,557,7" />
    </map>
</div>

这是JSFiddle

中的所有内容

1 个答案:

答案 0 :(得分:1)

我认为你的JSFiddle对于你想要的东西是正确的,除了一行。

更改

ctx.lineTo(poly[item], h - poly[item + 1]);

ctx.lineTo(poly[item], poly[item + 1]); 

因为0的坐标位于左上角,而不是左下角,因此您无需执行height - Y

<强>更新

您必须静态或以编程方式设置画布的宽度和高度。

静态:

<canvas id="map_canvas" style="z-index: 10; pointer-events: none;" width="615" height="457"></canvas>

以编程方式(基于图像大小):

var img = document.getElementById("MyImg");
var canvas = document.getElementById("map_canvas");
canvas.width = img.width;
canvas.height = img.height;