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.