簡體   English   中英

如何使用jquery訪問畫布?

[英]How to access the canvas using jquery?

我無法使用jquery訪問畫布ID。

我添加了jQuery庫。 但是當我點擊畫布ID時,我無法收到警報。

但是javascript工作正常。

    <script>
    $(document).ready(function(){
    $('#sq').click(function(){
    alert('test');
    });
    });
    </script>
    <canvas id="example" width="260" height="200">
        <h2>Shapes</h2>
      <p>A rectangle with a black border. In the background is a pink circle. Partially overlaying the 
      <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>. 
      Partially overlaying the circle is a green 
      <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();" id="sq">square</a> 
      and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>, 
      both of which are semi-opaque, so the full circle can be seen underneath.</p>
    </canvas>​

你在canvas元素中放置的所有內容都是后備內容 :它不會在現代瀏覽器中使用,因此你無法訪問它,你當然也無法點擊它。

在現代瀏覽器中正確使用canvas是使用其context繪制它。

來自MDN

<canvas>元素是一個HTML元素,可用於通過腳本(通常是JavaScript)繪制圖形。 例如,它可用於繪制圖形,制作照片合成,創建動畫或甚至進行實時視頻處理。

如果你想抓住canvas上的點擊,那就行了

$('#example').click(function(){ // <-- use the id of the canvas
    alert('test');
});

您不應該在canvas標記中放置html元素。 畫布的想法是使用代碼(也稱為javascript) 繪制它。 你正在做的事情不會起作用(或者只有當瀏覽器不支持畫布時才更有可能看到 - 這意味着非常古老的瀏覽器):)

從畫布中取出html元素並更改$('#sq').click(function(){ to $('#example').click(function(){

看看這個: http//jsfiddle.net/Zprb4/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM