简体   繁体   中英

Function or var not defined .js

I have a problem with the code below. I seem to be getting either var not defined or function not defined depending on where I place the brace (obviously). What I'm trying to accomplish is to convert an array into a string, in order to see what kind of data I have and how I should go about displaying it (histogram or something). This is the code:

function drawImage(imageObj) {
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var imageX = 10;
  var imageY = 10;
  var imageWidth = imageObj.width;
  var imageHeight = imageObj.height;

  context.drawImage(imageObj, imageX, imageY);

  var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
  var data = imageData.data;

  for (var i = 0, n = data.length; i < n; i += 4) {
    var red = data[i];
    var green = data[i + 1];
    var blue = data[i + 2];
    var alpha = data[i + 3];
  }
} //the brace that causes problems

function myFunction() {
  red.toString();
  document.getElementById("test").innerHTML = red;
}
// alternative position of brace?

var imageObj = new Image();

imageObj.onload = function() {
  drawImage(this);
};

imageObj.src = 'myimg.jpg';

Can somebody see where I have gone wrong with this?

Javascript has functional scope you can find more details here - variable scope .

By changing position of braces you are actually changing scope for myFunction function. When you will move curly braces after myFunction then it will become inner function for drawImage and get access to variable red .

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