2

hello Guys i was trying to copy an image pixel to a matrix so i can use it later. i was wondering if i was using the matrix in js correctly since i am a begginer thanks

<canvas id="Canvas" >  
     Navigator doesnt support canvas 
  </canvas>
      <script type="text/javascript">


  var img = new Image();

  img.src = "jj.JPG"; // Set source path

 img.onload = function() {
var matrix = [];
context.putImageData(idata, 0, 0);

for(var y = 0; y < canvas.height; y++) {

 matrix[y] = [];
for(var x = 0; x < canvas.width; x++){


var imgd = context.getImageData(x, y, canvas.width, canvas.height);
var pix = imgd.data;

var pos = (y * canvas.width + x) * 4; 
    matrix[y][pos]= pix[pos];;     //red      
    matrix[y][pos+1] =pix[pos+1];;    //bleu      
    matrix[y][pos+2]= pix[pos+2];;   //green       
    matrix[y][pos+3]= 255;          //alpha
}
  }
 </script>

 </body>
 </html>
2
  • 1
    It seems to me that the var pos = (y * canvas.width + x) * 4 comes from another piece of code which uses a one-dimensional array to represent the image data. Your matrix however is two-dimensional. You can flatten matrix simply by removing all the [y] parts. Commented Mar 19, 2017 at 1:05
  • le_m i have removed all the [y] so is it correct like this? thanks for helping me Commented Mar 19, 2017 at 1:17

2 Answers 2

1
for(var y = 0; y < canvas.height; y++) {//ligne
 matrix[y] = [];
for(var x = 0; x < canvas.width; x++){
//colonne

var imgd = context.getImageData(x, y, canvas.width, canvas.height);
var pix = imgd.data;


    var pos = (y * canvas.width + x) * 4; // position de pixel
    matrix[pos]= pix[pos];;           // some R value [0, 255]
    matrix[pos+1] =pix[pos+1];;           // some G value
    matrix[pos+2]= pix[pos+2];;           // some B value
    matrix[pos+3]= 255;           // set alpha channel
    }
 }
   return matrix;

}
Sign up to request clarification or add additional context in comments.

1 Comment

matrix[y] = [] doesn't seem right, you might want to remove it. Do you encounter any error when you run the code? Use console.log() or similar to get an idea of what the code does and if it does what you expect.
0
for(var y = 0; y < canvas.height; y++) {//ligne

for(var x = 0; x < canvas.width; x++){
//colonne

var imgd = context.getImageData(x, y, canvas.width, canvas.height);

   var pix = imgd.data;


    var pos = (y * canvas.width + x) * 4; // position de pixel
    matrix[pos]= pix[pos];;           // some R value [0, 255]
    matrix[pos+1] =pix[pos+1];;           // some G value
    matrix[pos+2]= pix[pos+2];;           // some B value
    matrix[pos+3]= 255;           // set alpha channel
    }
  }
   return matrix;

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.