O
O
oleg_m232019-07-18 16:58:20
JavaScript
oleg_m23, 2019-07-18 16:58:20

How to fix the error when calling drawImage?

An error is thrown in the console, I don’t understand what needs to be fixed:

Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
    at drawStuff (script.js:44)
    at resizeCanvas (script.js:38)
    at script.js:40
    at script.js:46
drawStuff @ script.js:44
resizeCanvas @ script.js:38
(anonymous) @ script.js:40
(anonymous) @ script.js:46

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <div>The canvas is the gray background color you see here. It will resize when you resize the browser, making it
        always fullscreen.</div>

    <canvas id="canvas"></canvas>
    
    
    <script src="script.js">
         (function () {

    let canvas = document.getElementById('canvas'),
        ctx = canvas.getContext('2d');

    // Reverce img in Base64
    function getBase64Image(url) {
        let promise = new Promise(function (resolve, reject) {

            let img = new Image();
           
            img.crossOrigin = "Anonymous";
            img.onload = function () {
                let canvas64 = document.createElement("canvas");
                canvas64.width = img.width;
                canvas64.height = img.height;               
                ctx.drawImage(img, 0, 0);
                let dataURL = canvas64.toDataURL("image/png");
                resolve(dataURL.replace(/^data:image\/(png|jpg|jpeg|pdf);base64,/, ""));
            };
            img.src = url;
        });

        return promise;
    };
   

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);

    function resizeCanvas() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        let url = "images/bg_ho.png";
        promise = getBase64Image(url);

        drawStuff();
    }
    resizeCanvas();

    function drawStuff() {
        
        ctx.drawImage(promise, 0, 0);
    }
})();
    </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2019-07-18
@profesor08

https://developer.mozilla.org/en/docs/Web/API/Canv...
The function accepts specific parameters and their types. You put something else in there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question