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
  • Just guessing but it may have to do with making logo.onload an async function. Commented Oct 31, 2019 at 12:23
  • I did that. Didn't work :/ Commented Oct 31, 2019 at 12:45

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I tried it. But no luck. you should consider that it works fine when I upload the second time
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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.