Html Canvas点击绘制图片的问题

需求是点击按钮在canvas上绘制指定图片,图片路径与html文件位置相同。使用onload时可正常加载,但使用click时无效。

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>Documenttitle>
    <link rel="stylesheet" href="./style.css">
head>
<body>
    <canvas>canvas>
    <div class="button_container">
        <button><img src="./1.png">Add Dog 1button>
    div>
body>
<script>
    let canva = document.querySelector("canvas");
    let context = canva.getContext("2d");
    let buttons = document.querySelector(".button_container").querySelectorAll("button");

    class image{
        constructor(path,xpos,ypos,height,width){
            this.path=path;
            this.xpos=xpos;
            this.ypos=ypos;
            this.height=height;
            this.width=width;
        }
    }

    let image1 = new image('1.png',10,50,100,100);

    buttons[0].addEventListener("click",draw(context,image1.path,image1.xpos,image1.ypos,image1.height,image1.width));

    function draw(context,path,xpos,ypos,height,width){
        let img = document.createElement('img');
        img.src=path;
        /*img.onload=function(){
            context.drawImage(img,xpos,ypos,height,width);
        }*/
        context.drawImage(img,xpos,ypos,height,width);
    }
script>
html>

请问导致问题的原因是什么?应当如何修改?

该回答引用GPTᴼᴾᴱᴺᴬᴵ
问题的原因是 buttons[0].addEventListener("click",draw(context,image1.path,image1.xpos,image1.ypos,image1.height,image1.width)); 这一行代码中的 draw 函数实际上被立即执行了,而不是在按钮点击时被调用。这是因为传递给 addEventListener 的第二个参数应该是一个函数,而不是一个函数调用的结果。

要解决这个问题,可以将该行代码改为以下形式:

buttons[0].addEventListener("click", function() {
  draw(context,image1.path,image1.xpos,image1.ypos,image1.height,image1.width);
});


这样,draw 函数就不会在代码加载时立即执行,而是在按钮点击时才被调用。


            buttons[0].addEventListener("click",function(){
                 draw(context, image1.path, image1.xpos, image1.ypos, image1.height, image1.width)
            }
            );