HYUTS
HYUTS

Reputation: 97

I am not using a loop correctly when using putImageData

I am reading rgb values from a file and trying to put them on canvas.

enter image description here

I have attempted many different variations of loops and increment values.

JavaScript:

function parseData(data) {
   var pixel_array = data.split('|');
   // Loop through pixel data from file
   for (i = 0; i < pixel_array.length; i += 4) {
         var [r, g, b] = pixel_array[i].split(',');
         imgData.data[i + 0] = r;
         imgData.data[i + 1] = g;
         imgData.data[i + 2] = b;
         imgData.data[i + 3] = 255;
   }
   ctx.putImageData(imgData, 0, 0);
};

Example of data format:

var data='84,133,165|84,133,165|85,133,165|86,135,167|87,136,168|88,137,169|89,138|'

I am getting the rgb values to the canvas but it is 1/4th the size that I would prefer. I would like an exact replica of the rgb values in my variable.

Upvotes: 0

Views: 94

Answers (2)

Kaiido
Kaiido

Reputation: 137016

Because pixel_array.length is the number of pixels in your data, you need to iterate it through one only.

But since ImageData.data uses 4 slots to represent one pixel, there you need to multiply by 4 your i variable.

var data='84,133,165|84,133,165|85,133,165|86,135,167|87,136,168|88,137,169|89,138|';
var pixel_array = data.split('|');
console.log(pixel_array.length); // 8

var imgData = new ImageData(4, 2);
console.log(imgData.data.length); // 32

// Loop through pixel data from file
for (let i = 0; i < pixel_array.length; i++) {
  const [r, g, b] = pixel_array[i].split(',');
  imgData.data[(i * 4) + 0] = r;
  imgData.data[(i * 4) + 1] = g;
  imgData.data[(i * 4) + 2] = b;
  imgData.data[(i * 4) + 3] = 255;
}
const ctx = canvas.getContext('2d');
ctx.putImageData(imgData, 0, 0);
// zoom for demo
ctx.imageSmoothingEnabled = false;
ctx.globalCompositeOperation = 'copy';
ctx.drawImage(canvas,10,10,10*canvas.width,10*canvas.height);
<canvas id="canvas"></canvas>

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44135

Because your loop counter is incrementing by four each time - just use ++:

for (i = 0; i < pixel_array.length; i++) {...}

Upvotes: 0

Related Questions