Load image as costume from URL

url as costume script pic


Nice! So you've read some source code. Do you understand what's happening here and can you explain to others who might be interested in writing such functions, what you are doing here and what gave you this idea? And also, what's potentially problematic about it, that it's a reentrant function?

Instead of adding attributes to the Process and of pushing contexts (which can easily break Snap! big-time) you could use a more Snap!-like approach, e.g.

What do you think?

I didn't really read the source code, I just read the source code for the HTTP/HTTPS library. Here's an explanation:

  • First, we check whether we already have an image as a attribute of the current process. If we don't we create one and we set the loaded attribute to true when the image finishes loading.
  • If the image does exist and it has finished loading we return the costume and set the img attribute to null.
  • Finally, if we just created the image or it hasn't finished loading we pop the current context by using the expression doYield and we create a new context to check whether the image has finished loading. This loops until the image has finished loading.

now how do we get a sound from a url?

probably something like:

var audio = new Audio(src);
return new Sound(audio, soundName);

I'm pretty sure external resource loading is asynchronous so the above code would be like

(assigning calling this function to a Snap! variable)

let sound = null;
const audio = new Audio(src);
audio.onload = () => {
  sound = new Sound(audio, costumeName);
return () => sound;

wait until (call (sound) :: control)
report (call (sound) :: control) :: control

Jens, I tried you're javascript function to load the weather icon from an api. Everything works fine until saving the project where I get the following error.

Thank you for the effort.

Can you post a link to the project?

Here it is: Snap! Build Your Own Blocks

Thanks - What URL is causing it to give the error on saving?

At the bottom the reporter

I'm thinking that this error may be significat and causing corruption of the image data and therefore the costume



buienradar script pic (1)

Thank you, this looks serious. In the mean time I should download the icons manually or use no icons at all. I stick with the latter.

You have to add img.crossOrigin = 'anonymous'; before img.onload = () => cst = new Costume(img);. and make sure the server sends CORS headers.

How do you do that?

Thanks - I can save the project now but have to stamp the icon costume and switch back to the Turtle costume.

I think like so...

Note: You need to request access to use cors-anywhere

How do you do that?