Loading a dynamic image in Processing.js

I am creating something that uses processing.js to work with JPEG images being dragged from a user computer to a canvas element. It currently works like this:

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 a .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()); } 

Everything is working fine. Now the problem: I would have thought that the requestImage callback (or loadImage, for that matter) will happen when the image is ready for rendering. However, if I do this:

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

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

+4
source share
2 answers

If the image upload failed, the callback will never be called. but imported_image.sourceImg reference to the real img element, maybe this will help. You can use it to determine the image loading status. ex: imported_image.sourceImg.complete ;imported_image.sourceImg.onerror;

+1
source

Actually, the best way I found for this is to check the loaded image property in the drawing loop. So:

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

Not a callback, but the same end result. There was more luck with this property than @DouO sourceImg.complete.

0
source

Source: https://habr.com/ru/post/1399279/


All Articles