2013-02-26 108 views
0

我的網頁加載2個東西的圖像和畫布。如何點擊第二張圖片

當頁面加載網頁加載圖片。 如果我點擊頁面加載畫布的地方。

現在我想如果我點擊圖片的一些事情發生,但怎麼說onclick - >當圖像被點擊。

我想我可以在我的照片中使用ID。但是,在創建圖片時,您如何在javascript中提供iD?

<script type="text/javascript"> 
function start() { 
     var vierkant = document.getElementById("Vierkant"); 

     initWebGL(vierkant);  // Initialize the GL context 

     // Only continue if WebGL is available and working 

     if (gl) { 
     gl.clearColor(0.0, 0.0, 5.0, 1.0);      // Set clear color to black, fully opaque 
     gl.enable(gl.DEPTH_TEST);        // Enable depth testing 
     gl.depthFunc(gl.LEQUAL);        // Near things obscure far things 
     gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);  // Clear the color as well as the depth buffer. 



     } 
    } 
function startImage() 
{ 
     var img = document.createElement("img"); 
     img.src = "Bus_Stop_2.png"; 
     document.body.appendChild(img); 
     img. 

} 


    function initWebGL(vierkant) { 
     // Initialize the global variable gl to null. 
     gl = null; 

     try { 
     // Try to grab the standard context. If it fails, fallback to experimental. 
     gl = vierkant.getContext("webgl") || vierkant.getContext("experimental-webgl"); 
     } 
     catch(e) {} 

     // If we don't have a GL context, give up now 
     if (!gl) { 
     alert("Unable to initialize your 'Vierkant'."); 
     } 
    } 

</script> 

    <body onclick="start()" onload="startImage()"> 
     <canvas id="Vierkant" width="640" height="480"> 
     Your browser doesn't appear to support the HTML5 <code>&lt;canvas&gt;</code> element. 
     </canvas> 
</body> 

回答

0

只是這樣做創建圖像後,

img.onclick = function() { alert('image clicked') }; 

你可以代替警告你的工作!

+1

事件處理程序的Javascript是區分大小寫的,因此您的代碼將無法正常工作,恐怕;它應該是'img.onclick' – JamieJag 2013-02-26 12:44:33

+0

是的,我注意到了!謝謝! – MJQ 2013-02-26 12:46:18

0

這應該工作:

function startImage() 
{ 
     var img = document.createElement("img"); 
     img.src = "Bus_Stop_2.png"; 
     document.body.appendChild(img); 
     img.onclick = function (evt) { 
      // do something here 
     }; 
} 

設置id,你可以使用:img.setAttribute('id', 'myid');