未捕获的类型错误:无法设置属性'onclick'为null.已尝试window.onload

Uncaught TypeError: Cannot set property 'onclick' of null. Tried window.onload

本文关键字:onclick null onload window 属性 类型 错误 设置      更新时间:2023-09-26

所以,我对Javascrip还比较陌生。虽然我想做的是给画布上的运动图像一个id,这样我最终就可以使用onclick将图像用作可点击的图像,这样我就可以将用户重定向到另一个页面,这就是点击图像时会发生的情况。这是我迄今为止的代码。我需要帮助。如果你需要更多的澄清,我会尽力进一步解释。

       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");
       }
       }

尝试:

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

应该提醒"达菲"。

您的问题是,您试图捕获文档中不存在的元素上的点击事件,因此用户无法点击。

当您调用var img = new Image()时,会创建一个新的<img>元素,其中包含您已经可以在javascript中修改的所有属性。但此元素仅可用于脚本,并且在调用document.anyElement.appendChild(img)之前不会显示在页面中。因此,与其把它看作一个元素,不如把它看作是一个imageObject(即使它实际上也是)。

文档中的<canvas>元素可供用户访问。因此,如果您想知道用户是否单击了,则必须将eventListener附加到此canvasElement。

但是canvasElement不知道它代表了什么。当您调用context.drawImage()时,您只是将imageSource中的像素应用于画布中的像素,对原始imageObject的所有引用都将丢失
要解决此问题,您必须将绘制图像的位置存储到画布中,然后检查捕捉到的单击事件是否在这些位置内。作为处理程序参数传递的Event的Click events的clientXclientY属性将为您提供事件发生时的光标位置。但是这些位置是相对于窗口的左上角的。因此,您还需要使这些相对于画布的左上角,这可以通过调用canvasElement的getBoundingClientRect()方法来完成。

下面是一个简化的例子:

// 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>

(您可能需要滚动才能真正看到图像,或者进入全屏)