简体   繁体   中英

window.onload that return a function

I tried to make a function that create a canvas with width and height how parameters. In an other file I called createCanvas(200,200), but the console give me an error:

Uncaught ReferenceError: createCanvas is not defined at main.js:1".

var context = undefined;
window.onload = function() {

  function createCanvas(w, h) {
    var canvas = document.createElement('canvas');

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

      width = canvas.width = h || 50;
      height = canvas.height = w || 50;
      document.body.appendChild(canvas);
    };
  };
  return createCanvas();
}

createCanvas is not defined in the global scope and you are referencing like it is.

This is good enough.

function createCanvas(w,h){
    var canvas = document.createElement('canvas');

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

        width = canvas.width = h || 50; 
        height = canvas.height = w || 50;
        document.body.appendChild(canvas);
    }
}

and in other file do, when the doc is ready :

 createCanvas(w,h)

Your createCanvas function is declared inside the window.onload event handler, which means it's only declared locally and not visible to other code. Also, you can't return a value from an event handler. It isn't called by any part of your code that could capture the return value. It runs as an 'asynchronous' function. Something you might investigate later on.

A simple way to make it available to other code is to assign it to a global variable. eg

var  createCanvas;  *outside the onload event handler*

and then in your event handler do

createCanvas = function(w,h){...

This following uses a button to create a canvas for a given width and height. Added a color just to ensure it was working.

 var context = undefined; var btnCanvas = document.getElementById("createCanvas"); btnCanvas.addEventListener('click',function(e){ createCanvas(200,200); }); function createCanvas(w,h){ var canvas = document.createElement('canvas'); canvas.setAttribute("style","background-color: red;"); if(context == undefined){ context = canvas.getContext('2d'); width = canvas.width = h || 50; height = canvas.height = w || 50; document.body.appendChild(canvas); }; }; 
 <button id="createCanvas">Create Canvas</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM