I am currently trying to get RGB data for a texture image, while displaying a preview of the texture to the user.
The user drops an image file into the form, and it should show the preview of the image, while drawing the image to an canvas to get the RGB values for each pixel:
handleTextureImageDrop = (e) ->
e.stopPropagation()
e.preventDefault()
if e.dataTransfer.files.length >= 1
file = e.dataTransfer.files[0]
if file
reader = new FileReader()
reader.onload = (loadEvent) ->
img = $ '<img/>'
img.attr
src: loadEvent.target.result
$(e.target).html img
reader.onloadend = (loadendEvent) ->
img = $(e.target).children 'img'
width = img.width()
height = img.height()
canvas = $ '<canvas/>',
width: width
height: height
$('#wrapper').append canvas
context = $('canvas').get(0).getContext '2d'
context.drawImage img.get(0), 0, 0
rgb = (for x in [0...width]
for y in [0...height]
context.getImageData(x, y, 1, 1).data)
canvas.remove()
TEXTURE_FILES.push
image: file.name
rgb: rgb
reader.readAsDataURL file
As it stands it works about 50% of the time, but the rest of the time width and height are set to 0, so the iteration across the pixel data never happens.
This would suggest to me that there is some sort of race condition happening where the image hasn’t loaded into the <img/> tag yet.
Is that what is happening? Or am I missing something silly and obvious?
Any help would be much appreciated.
You will get correct width and height only after the image has been loaded. Usually
$(img).loadis used for this.I am not familiar with coffeescript, so I am not able to understand whether you are doing this in your current code. If not please try it.