How to get a P5 image into the DOM?

Hi
I want to get an internally created image file (not loaded or from a url) into the DOM. I’m sure it’s really simple, but have no idea, thanks.

What do you mean by into the DOM?
Where will it be saved? I don’t think you can upload an image to the web editor dynamically.
You can save it into your download folder.

let img;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  line(0, 0, width, height);
  line(width, 0, 0, height);
}

function mousePressed() {
  img = get();
  img.save('image','png');
}

okay I’ll try and clarify my problem,
Im using ML5.js to create a browser app that features neural style transfer. The user can create an image in P5.js and then the style transfer processes this image. However - the style transfer process (as far as I can get working) can only happen in the HTML / DOM side as an , this is because the tensorflow process needs WebGL.

So, more simply I need get a P5.image into the same format as a createImg() - created as an element in the DOM.

I hope that makes sense!

createImg() creates a p5.Element wrapping an <img> DOM element which can be accessed via its property elt:
p5js.org/reference/#/p5.Element/elt

On the other hand a p5.Image is a wrapper for a <canvas> DOM element which can be accessed via its property canvas:
p5js.org/reference/#/p5.Image

Unfortunately p5.Image uses a CanvasRenderingContext2D accessed via its property drawingContext:

3 Likes

Hi,
Thx, I’m aware of all of the above - but I still don’t know how to solve my problem.

e.g.
I have an image ‘myImage’ which was created with createImage()… NOT createImg() or loadImage().

I need to convert / copy across ‘myImage’ into the DOM.

As I’ve stated a p5.Image contains a <canvas> DOM element accessible via its canvas property:

You need to search that library’s docs for which datatypes it can work with.

For example whether it can accept an HTMLCanvasElement.

You may also attempt to invoke method HTMLCanvasElement::toDataURL() over a p5.Image::canvas and use it as the 1st argument for createImg():
p5js.org/reference/#/p5/createImg

1 Like

ok - thanks - these ideas seem useful - I’ll give it a try :slight_smile:

Hey,
Thanks again for your help - I got everything working.
I basically just drew my image onto the canvas - then took a ‘snap shot’ of it with toDataURL() and popped that inside createImg like you said… voila…

1 Like

Congratz! :partying_face: So you did something like this I believe: :stuck_out_tongue:const snapshot = createImg(canvas.toDataURL()).hide();

haha - my code is no where near as elegant - but I don’t care - it works!