0

I'm trying to draw an image (uploaded) on a canvas in react js.

onChange = (e) => {
  var file = URL.createObjectURL(e.target.files[0])
  const logo = new Image()
  logo.crossOrigin = "anonymous";
  const canvas = document.getElementById("canvas3")
  const ctx = canvas.getContext("2d")
  logo.onload = async function() {
    canvas.height = logo.naturalHeight
    canvas.width = logo.naturalWidth
    ctx.drawImage(logo, 0, 0, logo.naturalWidth, logo.naturalHeight, 0, 0, ctx.canvas.width,
      ctx.canvas.height)
  }

  logo.src = this.state.logoFile
  const c = document.getElementById("canvas3")
  console.log(c.toDataURL())
}
<label className="logoUpload">
    <input type="file" onChange={this.onChange} required />
    <span>Upload logo</span>
</label>
<canvas id="canvas"></canvas>

when I try to upload an image for the first time it doesn't work, But second time it draws. I don't understand why is this happening.

2 Answers2

0

Try switching your onChange syntax to onChange={(e) => this.onChange(e)}

Another option might be to wrap the input in a <div> and move the onChange handler there.

reference: React input onChange won't fire

Mike
  • 106
  • 5
0

I solved my problem by adding await to URL.createObjectURL(e.target.files[0]) and made function async. The problem is I'm updating the img src without the url loaded. So, await worked.

  • URL.createObjectURL() is synchronous, awaiting for it will do nothing more than move to a microtask. You probably got fooled by something else in thinking it's what solved your issue, but it's clearly not. – Kaiido Nov 01 '19 at 04:25