Canvas-drawImage cannot draw, and there is a blank solution

table of Contents:


Problem analysis

When operating a drawImage()function, it often canvashappens that the call is normal, but the drawing is blank:

Insert picture description here

In this case, the reasons can be classified as:

  • When the browser loads the picture, the picture has not been loaded yet, so start drawing
  • The main reason is: drawImage()asynchronous function

Solution

  1. drawImage()Function, wait until imgthe image specified in the label is loaded, and then start drawing, otherwise there will be no image

  2. Two loading methods can be declared:

    1. img.onload = function() {drawImage()}
    2. window.onload = function() {drawImage()}
  3. Can be used addEventListener('load', () => {drawImage()}), can draw the image

    1. The same goes for:document.querySelector('#imgs').addEventListener('load', (event) => {drawImage()})

Example code

 let img = document.getElementById('imgs');
        // 会加载出图片	
        img.addEventListener('load', ()=> {
    
    
            ctx.drawImage(img, 20, 20);
        });
        // 会加载出来图片
        img.onload = () => {
    
    
            ctx.drawImage(img, 20, 20);
        }

effect:
Insert picture description here

Test sample

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    img <br />
    <img id="imgs" width="240" height="240" src="../../img/show.jpg">
    <hr />
    canvas<br />
    <canvas id="canvas" width="500" height="350"></canvas>
    <script>
        let c = document.getElementById('canvas');
        let ctx = c.getContext('2d');

        let img = document.getElementById('imgs');
        // 会加载出图片
        img.addEventListener('load', () => {
     
     
            ctx.drawImage(img, 20, 20);
        });
        // 会加载出来图片
      /*   img.onload = () => {
            ctx.drawImage(img, 20, 20);
        } */
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/u013362192/article/details/113922101