需求是点击按钮在canvas上绘制指定图片,图片路径与html文件位置相同。使用onload时可正常加载,但使用click时无效。
<!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>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<canvas></canvas>
<div class="button_container">
<button><img src="./1.png">Add Dog 1</button>
</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>
请问导致问题的原因是什么?应当如何修改?