2016-04-29 5 views
0

Also, ich bin relativ neu zu Javascrip. Allerdings möchte ich ein Bewegtbild auf meiner Leinwand eine ID geben, damit ich mit onclick das Bild letztendlich als klickbares Bild verwenden kann, damit ich den Benutzer auf eine andere Seite umleiten kann, was passieren würde, wenn der Bild wird angeklickt. Hier ist mein Code soweit. Ich brauche Hilfe. Wenn Sie weitere Erläuterungen benötigen, werde ich versuchen, dies näher zu erläutern.Uncaught TypeError: Eigenschaft 'onclick' von null kann nicht festgelegt werden. Versuchte window.onload

 var ctx; 
     var imgBg; 
     var imgDrops; 
     var x = 0; 
     var y = 0; 
     var noOfDrops = 50; 
     var fallingDrops = []; 
      function drawBackground(){ 
    ctx.drawImage(imgBg, 0, 0); //Background 
      } 
      function draw() { 
    drawBackground(); 

    for (var i=0; i< noOfDrops; i++) 
    { 
    ctx.drawImage (fallingDrops[i].image, fallingDrops[i].x, fallingDrops[i].y); //The rain drop 

    fallingDrops[i].y += fallingDrops[i].speed; //Set the falling speed 
    if (fallingDrops[i].y > 1000) { //Repeat the raindrop when it falls out of view 
    fallingDrops[i].y = -25 //Account for the image size 
    fallingDrops[i].x = Math.random() * 10000; //Make it appear randomly along the width 
       } 

       } 
      } 
      function setup() { 
    var canvas = document.getElementById('canvasRegn'); 

    if (canvas.getContext) { 
      ctx = canvas.getContext('2d'); 

       imgBg = new Image(); 
     imgBg.src = "http://images.susu.org/unionfilms/films/backgrounds/hd/space-jam.jpg"; 
    setInterval(draw, 36); 
    for (var i = 0; i < noOfDrops; i++) { 
     // Charles Barkley 
     var fallingDr = new Object(); 
     fallingDr["image"] = new Image(); 
     fallingDr.image.src = 'http://xenboards.ignimgs.com/external_data/attachments/8/8795-f09b907a01726a25ca2fbd2f588e3f0e.jpg'; 
     fallingDr["x"] = Math.random() * 10000; 
     fallingDr["y"] = Math.random() * 5; 
     fallingDr["speed"] = 3 + Math.random() * 5; 
     fallingDrops.push(fallingDr); 
     // Bugs bunny 
     var fallingDr2 = new Object(); 
     fallingDr2["image"] = new Image(); 
     fallingDr2.image.src = 'http://i.imgur.com/zN2CSAf.png' 
     fallingDr2["x"] = Math.random() * 10000; 
     fallingDr2["y"] = Math.random() * 5; 
     fallingDr2["speed"] = 3 + Math.random() * 5; 
     fallingDrops.push(fallingDr2); 
     // Michael Jordan 
     var fallingDr3 = new Object(); 
     fallingDr3["image"] = new Image(); 
     fallingDr3.image.src = 'http://i.imgur.com/XxvJiGg.png' 
     fallingDr3["x"] = Math.random() * 10000; 
     fallingDr3["y"] = Math.random() * 5; 
     fallingDr3["speed"] = 3 + Math.random() * 5; 
     fallingDrops.push(fallingDr3); 
     // Daffy duck 
     var fallingDr4 = new Object(); 
     fallingDr4["image"] = new Image(); 
     fallingDr4.image.src = 'http://i.imgur.com/QZogw2L.png' 
     fallingDr4["x"] = Math.random() * 10000; 
     fallingDr4["y"] = Math.random() * 5; 
     fallingDr4["speed"] = 3 + Math.random() * 5; 
     fallingDrops.push(fallingDr4); 
     fallingDr4.image.id = "Daffy"; 
     } 
    } 
      } 
     setup(); 
     window.onload = function(){ 
      document.getElementById("Daffy").onclick=function(){ 
     alert("Hello World"); 
     } 
     } 
+0

Sie versuchen zu setzen die Eigenschaft "onclick" von 'document.getElementById (" Daffy ")' und den Fehler, dass Sie die Eigenschaft "onclick" von null nicht festlegen können. Es ist wahrscheinlich, dass 'document.getElementById (" Daffy ")' null zurückgibt, weil du keine Elemente mit der ID "Daffy" in deinem DOM hast. – Hamms

Antwort

1

Versuchen:

fallingDr4.image.onclick=function(){ 
     alert(this.id); 
     } 

sollte alarmieren "Duffy".

+0

Ich danke dir sehr, aber wenn ddr4 gedrückt wird, passiert immer noch nichts –

+0

Das ist rätselhaft. .. Diese Codezeile sollte an einen Platz wie folgt gesetzt werden: 'var fallingDr4 = new Object(); fallingDr4 ["image"] = neues Bild(); fallingDr4.image.src = 'http://i.imgur.com/QZogw2L.png'; fallingDr4.image.onclick = function() { Warnung (this.id); }; fallingDr4 ["x"] = Mathematik.random() * 10000; fallingDr4 ["y"] = Math.random() * 5; fallingDr4 ["Geschwindigkeit"] = 3 + Math.random() * 5; fallingDrops.push (fallingDr4); fallingDr4.image.id = "Daffy"; } } ' –

0

Ihr Problem besteht darin, dass Sie versuchen, das Klickereignis für ein Element abzufangen, das nicht im Dokument ist und daher vom Benutzer nicht angeklickt werden kann.

Wenn Sie var img = new Image() anrufen, wird ein neues Element erstellt, mit all seinen Eigenschaften, die Sie bereits in Ihrem Javascript ändern können. Dieses Element ist jedoch nur für Ihre Skripts verfügbar und wird erst auf der Seite angezeigt, wenn Sie document.anyElement.appendChild(img) aufrufen. Es ist also besser, dies als ein imageObject mehr als ein Element zu betrachten (auch wenn es tatsächlich auch ist).

In Ihrem Dokument befindet sich das Element <canvas>, das für Ihren Benutzer zugänglich ist. Wenn Sie also wissen möchten, ob der Benutzer geklickt hat, müssen Sie eventListener an dieses canvasElement anhängen.

Aber das canvasElement weiß nicht, was es darstellt. Wenn Sie context.drawImage() aufrufen, wenden Sie nur die Pixel aus der imageSource auf die Canvas an, und alle Referenzen auf das ursprüngliche imageObject gehen verloren.
Um dies zu umgehen, müssen Sie die Position des gezeichneten Bildes in der Arbeitsfläche speichern und dann überprüfen, ob sich das Klickereignis innerhalb dieser Positionen befindet. Klicken Sie auf Ereignisse 'clientX und clientY Eigenschaften des Ereignisses übergeben als Argumente des Sie Handlers gibt Ihnen die Position des Cursors, wenn das Ereignis aufgetreten ist. Die Positionen sind jedoch relativ zur oberen linken Ecke des Fensters. Sie müssen diese also relativ zur oberen linken Ecke der Zeichenfläche festlegen, indem Sie die Methode getBoundingClientRect() des canvasElement aufrufen. Hier

ist ein vereinfachtes Beispiel:

// this function will be called at image's load 
 
var init = function() { 
 
    // a reference to our "in-screen" canvasElement 
 
    var canvas = document.getElementById('canvas'); 
 
    var ctx = canvas.getContext('2d'); 
 
    // "kitty" will be the js object that will help us know if we clicked on our image 
 
    // "this" refers to the imageObject 
 
    var kitty = { 
 
     width: this.width, 
 
     height: this.height, 
 
     // random positions 
 
     left: Math.random() * (canvas.width - this.width), 
 
     top: Math.random() * (canvas.height - this.height), 
 
    }; 
 
    // draw our image at the random positions we created 
 
    ctx.drawImage(this, kitty.left, kitty.top, kitty.width, kitty.height); 
 
    // here we're listening to mousemove event, 
 
    // but click event shares the same clientX & clientY properties 
 
    var moveHandler = function(evt) { 
 
     // in the "evt" object passed, we can get the x and y positions relative to the window 
 
     // so we make these relatives to the canvas ones 
 
     var canvasRect = canvas.getBoundingClientRect(); 
 
     var x = evt.clientX - canvasRect.left; 
 
     var y = evt.clientY - canvasRect.top; 
 

 
     // now we've got our relative positions, we can check if we were inside the image 
 
     if (x >= kitty.left && x <= (kitty.left + kitty.width) && y >= kitty.top && y <= (kitty.top + kitty.height)) { 
 
      // we are over the image, do something 
 
      canvas.style.cursor = 'pointer'; 
 
      document.body.style.backgroundColor = 'lightblue'; 
 
     } else { 
 
      canvas.style.cursor = 'default'; 
 
      document.body.style.backgroundColor = 'transparent'; 
 
     } 
 
     }; 
 
     // attach this event handler to the canvasElement 
 
     canvas.addEventListener('mousemove', moveHandler); 
 
    }; 
 

 
// this will create an imageObject, which will stay "off-screen" (never appendded to the document) 
 
var img = new Image(); 
 
// wait that the image has loaded before trying to make any magic 
 
img.onload = init; 
 

 
img.src = "http://lorempixel.com/200/70/cats";
body { 
 
    width: 100vw; 
 
    text-align: center; 
 
} 
 
canvas { 
 
    margin: 0 auto; 
 
    position: relative; 
 
}
<canvas id="canvas" width="500" height="500"></canvas>

(Sie müssen möglicherweise blättern, um tatsächlich das Bild zu sehen, oder gehen Vollbild)

Verwandte Themen