使用canvas html5创建一个二维图像像素数组

时间:2017-03-19 01:02:48

标签: javascript html5 canvas pixels

你好伙计们我​​试图将图像像素复制到矩阵中,以便我以后可以使用它。我想知道我是否正确使用js矩阵,因为我是一个begginer谢谢你          

<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 个答案:

答案 0 :(得分:0)

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;

}

答案 1 :(得分: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;

 }