S
S
SpeNch2021-04-11 17:47:47
Canvas
SpeNch, 2021-04-11 17:47:47

Why is there an error when calling drawImage?

Why is there an error when calling drawImage?

<body></body>
<script>
const canvas = document.createElement('canvas')
canvas.width = 400
canvas.height = 300
document.body.appendChild(canvas)
var ctx = canvas.getContext('2d')
const setBg = () => ctx.drawImage("https://mdn.mozillademos.org/files/225/Canvas_drawimage.jpg", 0, 0)
const background = document.createElement('img')
background.setAttribute('crossorigin', 'anonymous')
background.onload = setBg
const downloader = document.createElement('a')
downloader.style.display = 'none'
document.body.appendChild(downloader)
downloader.download = 'myimage.png'
setTimeout(() => {
  ctx.drawImage("https://mdn.mozillademos.org/files/225/Canvas_drawimage.jpg", 0, 0)
  save();
}, 2000)

function save() {
  downloader.href = canvas.toDataURL()
  downloader.click()
}
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2021-04-11
@SpeNch

Because it is not necessary to give a link there, but an Image object.
like this

let img = new Image();
img.src = "https://mdn.mozillademos.org/files/225/Canvas_drawimage.jpg",
img.onload = function(){
  ctx.drawImage(img, 0, 0)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question