2013-07-12 27 views
0

圖像這是我的代碼:如何在畫布上查看多個圖像

<!DOCTYPE HTML> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
    <!--<script type="text/javascript" src="js/jquery-ui.js"></script> 
    <script src="js/jquery-ui-1.8.20.js" type="text/javascript"></script> 
    <script src="js/jquery-ui-1.8.20.min.js" type="text/javascript"></script>--> 
    <head> 

    <body> 
    <canvas id="myCanvas" width="940" height="600" style="border:1px solid #c3c3c3;"> 
    Your browser does not support the canvas element. 
    </canvas> 
    <script type="text/javascript"> 
     function ImageLoad() 
     { 
      var ctx = document.getElementById('myCanvas').getContext('2d'); 

      var img = new Image(); // Create new img element 
      img.onload = function(){ 
       // execute drawImage statements here This is essential as it waits till image is loaded before drawing it. 
       ctx.drawImage(img , 0, 0); 

      }; 
      img.src = $('img[alt="example"]').attr('src'); // Set source path 

     } 
    </script> 
    <!--<img src="basicCycle.jpg"/>--> 
    <table border="1px"> 
    <tr> 
    <td><a href="javascript:ImageLoad()"><img src="cycle6.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle1.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle2.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle3.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle4.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle5.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle6.jpg" alt="example" height="120" width="120"></a></td> 
    <td><a href="javascript:ImageLoad()"><img src="cycle1.jpg" alt="example" height="120" width="120"></a></td> 
    </tr> 
    </table> 
    </body> 
    </html> 

現在我想加載CYCLE1在畫布上,當我點擊CYCLE1 image.and負載循環2,當我點擊循環2圖像。 問題是我的代碼總是加載第一個td image.whatever我點擊。

+0

但你有什麼嘗試? – simonzack

回答

0

問題是,您總是將src設置爲alt爲「example」且所有圖像都具有該alt的圖像的src,因此您始終會獲得第一個圖像。

相反的:

img.src = $('img[alt="example"]').attr('src'); // Set source path 

這樣做:

img.src = $(this).find('img').attr('src'); 

「這」 指的是被點擊的鏈接,但你需要用 「#」 替換HREF值:

<td><a href="#"><img src="cycle1.jpg" alt="example" height="120" width="120"></a></td> 

並把這個權利關閉之前<script>標籤:

$(document).ready(function() { 
    $('a').click(ImageLoad); 
}); 

你也應該把:

return false; 

爲內部ImageLoad最後一行()。如果已經滾動,這將使頁面跳轉到頂部。