M
M
MrChen2019-10-09 14:45:38
JavaScript
MrChen, 2019-10-09 14:45:38

How to get the canvas image that draws the image?

Hello! I ran into this problem: I create a canvas element, then draw an image on it, but when I get a link to the image using toDataUrl and follow it, the image that the canvas drew is not displayed.
Here is my code:

var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')

    canvas.width = 500
    canvas.height = 500

    var backgroundImg = document.createElement("img");

    backgroundImg.src = "https://i.imgur.com/yf6d9SX.jpg";

    backgroundImg.onload = () => {
        ctx.drawImage(backgroundImg, 0, 0, canvas.width,canvas.height);   
    }

    console.log(canvas.toDataURL("image/jpg"))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2019-10-09
@dollar

You create asynchronous code in onload that should run after the image is loaded. Even if it is already loaded and waiting in the cache, this piece of code will still run immediately after the current piece of code.
But before that , the current piece of code must end, at the end of which you output the canvas to a string. And of course, there is nothing there.
After console.log is executed, the image will be drawn on the canvas (in onload).
PS When you fix this error, you will encounter the following one. But that will be another question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question