0
\$\begingroup\$

I need to count non-transparent pixels in a canvas. I am pretty sure there is a nice and elegant syntax for doing this. Note that the data returned by getImageData is not a regular array and cannot be sliced, for example, or it does not have a reduce method.

data = context.getImageData(0, 0, canvas.width, canvas.height).data
count = 0
i = 0
for x in data
  if (i + 1) % 4 == 0 && x > 0
    count++
  i++
\$\endgroup\$
4
\$\begingroup\$

What about this?!

data = context.getImageData(0, 0, canvas.width, canvas.height).data
count = 0
count++ for x, i in data when (i+1) % 4 is 0 and x > 0
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.