0

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?

Andy
  • 61,948
  • 13
  • 68
  • 95
Micke
  • 29
  • 5
  • 1
    You're not calling `myFunction` anywhere, but even if you did it wouldn't have access to `red` which is scoped locally to the previous function. – Andy Oct 06 '17 at 20:24
  • `red.toString();` as a statement won't do anything. – Pointy Oct 06 '17 at 20:26
  • why you have myFunction ? You can not use red inside your myFunction. javascript has functional scope for variables. – Anshul Oct 06 '17 at 20:26
  • @Andy I'm actually calling (left that part out of the code) it, but like you say it doesn't access var red. – Micke Oct 06 '17 at 20:28
  • Previous comments, plus: drawImage(this) could be drawImage(imageObj) instead. I'm not sure what 'this' would be in your onload callback. – Kieveli Oct 06 '17 at 20:32

1 Answers1

0

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.

Anshul
  • 9,312
  • 11
  • 57
  • 74
  • Javascript has block scoping as well. – Rajaprabhu Aravindasamy Oct 06 '17 at 20:51
  • Thanks for the comments so far, especialy @Anshul. If I use var data I get all the RGBA values for my image, but only one value for var red. It seems that the for loop doesn't do what it's supposed to. I use a 20 x 20 px image so I should have 400 values for red, since var data has 1600 right? – Micke Oct 07 '17 at 06:09