在canvas上監聽event,最簡單的方式,就是將event綁在canvas,但是當canvas畫上各種不同的shape時,這時就必須另外實作監聽各個shape的event。另一種方式,則是在canvas上,在疊加一塊image或html5的svg(利用現成html的tag),用來監聽不規則的形狀。
用image的方式,則是搭配map和area tag,這種方式再大部份的瀏覽器都支援。
以下是個map tag搭配canvas的example:
<canvas id="canvas" width="200" height="200"></canvas>
<img src="" width="200" height="200" usemap="#map" style="border:0px;position:absolute;z-index:1;opacity:0;" id="mapImage" />
<map name="map" id="map">
<area id="areaCircle" shape="circle" coords="75,75,10" href="#" />
</map>
image上的usemap屬性,是用來參照map tag的名稱,而area則是設定監聽的範圍,和綁定event的tag,範例都以圓形為例。圓的coords(x,y,r),r為半徑。
var $canvas = $("#canvas");
$("#mapImage").offset({
top:$canvas.offset().top,
left:$canvas.offset().left
});
$("#areaCircle").on("click",function(){
alert("click");
});
//get a reference to the canvas
var ctx = $canvas[0].getContext("2d");
//draw a circle
ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
上面程式做的事情,先將image疊在canvas上,綁定好event,接著用canvas畫一個圓。[map tag可參考w3c](http://www.w3schools.com/tags/tag_area.asp)
##### svg搭配canvas的example:
<canvas id="canvas" width="200" height="200"></canvas>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg" style="position:absolute;z-index:1;opacity:0;">
<circle id="circle" cx="75" cy="75" r="10" stroke="black" stroke-width="0" style="cursor:pointer;opacity:0;"/>
</svg>
svg與map tag不同的是,map tag必須指定image作為參照,而svg可以自己產生不同的shape,這裡的範例是用來搭配canvas使用,所以會設定為透明。
$("circle").on("click",function(){
alert("click");
});
var $canvas = $("#canvas");
$("#svg").offset({
top:$canvas.offset().top,
left:$canvas.offset().left
});
//get a reference to the canvas
var ctx = $canvas[0].getContext("2d");
//draw a circle
ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI2, true);
ctx.closePath();
ctx.fill();