Evangelism/Firefox3.5/35Days/Articles/createImageData: Difference between revisions

no edit summary
No edit summary
Line 15: Line 15:


  canvasData {
  canvasData {
   width: ''unsigned long'' // the width of the canvas,
   width: ''unsigned long'', // the width of the canvas
   height: ''unsigned long'' // the height of the canvas,
   height: ''unsigned long'', // the height of the canvas
   data: ''CanvasPixelArray'' // the values of the pixels
   data: ''CanvasPixelArray'' // the values of the pixels
  }
  }
Line 65: Line 65:
  for (var x = 0; x < canvasData.width; x++) {
  for (var x = 0; x < canvasData.width; x++) {
   for (var y = 0; y < canvasData.height; y++) {
   for (var y = 0; y < canvasData.height; y++) {
 
     // Index of the pixel in the array
     // Index of the pixel in the array
     var idx = (x + y * width) * 4;
     var idx = (x + y * width) * 4;
 
     // If you want to know the values of the pixel
     // If you want to know the values of the pixel
     var r = canvasData.data[idx + 0];
     var r = canvasData.data[idx + 0];
Line 75: Line 75:
     var a = canvasData.data[idx + 3];
     var a = canvasData.data[idx + 3];
     //[...] do what you want with these values
     //[...] do what you want with these values
 
     // If you want to update the values of the pixel
     // If you want to update the values of the pixel
     canvasData.data[idx + 0] = ...; // Red channel
     canvasData.data[idx + 0] = ...; // Red channel
Line 90: Line 90:
=== Examples ===
=== Examples ===


=== getImageData ===
== getImageData ==
Here is a code that transform your image to a gray scale:
Here is a code that transform your image to a gray scale:


Line 98: Line 98:
  for (var x = 0; x < canvasData.width; x++) {
  for (var x = 0; x < canvasData.width; x++) {
   for (var y = 0; y < canvasData.height; y++) {
   for (var y = 0; y < canvasData.height; y++) {
 
     // Index of the pixel in the array
     // Index of the pixel in the array
     var idx = (x + y * width) * 4;
     var idx = (x + y * width) * 4;
 
     // The RGB values
     // The RGB values
     var r = canvasData.data[idx + 0];
     var r = canvasData.data[idx + 0];
     var g = canvasData.data[idx + 1];
     var g = canvasData.data[idx + 1];
     var b = canvasData.data[idx + 2];
     var b = canvasData.data[idx + 2];
 
     // Update the values of the pixel;
     // Update the values of the pixel;
     var gray = (r + g + b) / 3;
     var gray = (r + g + b) / 3;
Line 116: Line 116:
  canvas.putImageData(canvasData, 0, 0);
  canvas.putImageData(canvasData, 0, 0);


=== createImageData ===
== createImageData ==
Here is a code the draw a fractal:
Here is a code the draw a fractal:


Confirmed users
591

edits