Question

I'm building something that uses processing.js to operate on JPEG images dragged from a users machine into a canvas element. Currently, it works like so:

canvas.addEventListener("dragenter", dragEnter, false);
canvas.addEventListener("dragexit", dragExit, false);
canvas.addEventListener("dragover", dragOver, false);
canvas.addEventListener("drop", drop, false);
...
function drop(evt) {
...
    var files = evt.dataTransfer.files;
    handleFiles(files);
}
function handleFiles(files) {
    var file = files[0];
    reader = new FileReader();
    reader.onloadend = handleReaderLoadEnd;
    reader.readAsDataURL(file);
}
function handleReaderLoadEnd(evt) {
    var p=Processing.getInstanceById('canvas');
    p.setImage( evt.target.result );
}

...in JS, then in the .pjs script attached to the canvas (<canvas datasrc="/assets/draw.pjs" id="canvas" width="978" height="652">):

PImage imported_image;
void setImage(s) {
    imported_image = requestImage(s , "" , image_loaded_callback());
}

All working fine so far. Now the problem: I would have thought the callback on requestImage (or loadImage for that matter) would happen when the image is ready to render. However if I do this:

void image_loaded_callback() {
    image(imported_image, 0, 0);
}

nothing renders. I can get round the problem by waiting 10 frames and then rendering, but that seems like a very ugly (and probably unreliable) solution. Are there any better ways to do this? Any help much appreciated!

Was it helpful?

Solution

if the image loading failed, the callback will never call. but imported_image.sourceImg referent to the real img element, may be this will help. you can use it to detect the image load state. ex: imported_image.sourceImg.complete ;imported_image.sourceImg.onerror;

OTHER TIPS

Actually, the best way I've found to do this is checking the loaded property of the image in the draw loop. So:

void draw() {
    if(imported_image != null ) {
        if(imported_image.loaded) {
           image(imported_image,0,0,500,500);
        }
    }
}

Not a callback, but same end result. Had more luck with that property than @DouO's sourceImg.complete.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top