Molly
Molly

Reputation: 153

can javascript select a user's image to insert on a webpage without uploading to a server?

I have an X3D page with some solid primitives. I want the user to be able to select her own image to be used as a texture, but I want the page to be all client side.

Can JavaScript insert an image into the HTML without uploading the image to a server? I have a vague memory of seeing this option somewhere. The image was changed to a PNM and inserted as text and then reconverted to an image for display/processing. I cannot find a reference anywhere and I may be using the wrong search terms. There are webpages (i think) that ask for an image to be selected for display without ever uploading. What is this function/script called? Has some other js function been developed that does this more efficiently? Have I gone mad?

JavaScript does this all the time with text. fill out a form and see the text right there.

My example X3D is below.

enter code here

enter code here enter code here

enter code here    <shape>
    <appearance>
      <material diffuseColor='0.5 0.2 1.0'> </material>
      <ImageTexture url=' "THE_CLIENT_IMAGE.png" '></ImageTexture>
    </appearance>
    <sphere radius="3" > </sphere>
    </shape>
</Transform>

Upvotes: 0

Views: 538

Answers (1)

Konrad
Konrad

Reputation: 24691

Working snippet:

const img = document.querySelector('#img')
document.querySelector('#file').addEventListener('input', event => {
  if (event.target.files.length === 0) {
    console.error('No file provided')
    return
  }
  const reader = new FileReader()
  reader.addEventListener('loadend', () => {
    img.src = reader.result
  })
  reader.readAsDataURL(event.target.files[0])
})
<input type="file" id="file">
<img id="img">

Change <img> to ImageTexture and done

Upvotes: 1

Related Questions