gpt4 book ai didi

javascript - 禁用点击 EventListener

转载 作者:行者123 更新时间:2023-11-30 16:38:03 25 4
gpt4 key购买 nike

我正在尝试学习 HTML5 Canvas 。在出现吃 cookies 的猫 gif 之前,第一张图片需要点击七次。最初,我将 click EventListener 绑定(bind)到图像。出现吃 cookies 的猫 gif 后,我无法禁用点击。有什么建议吗?

cat.html

<!DOCTYPE html>
<html>
<head>
<title>Cat Animation</title>
</head>
<body>
<div id="canvasDiv"></div>
<script type="text/javascript" src="cat.js"></script>
<script type="text/javascript">
prepareCanvas(document.getElementById("canvasDiv"), 700, 700);
document.getElementById("canvas").addEventListener("click", function(){console.log("clicked");loadImage("cat");console.log(total);console.log(currentFrame);}, false);
</script>
</body>
</html>

猫.js

var canvas;
var context;
var image;
var currentFrame = 0;
var frames = 4;
var width = 350;
var height = 300;
var total = 0
var finalFrame = 0;

function prepareCanvas(canvasDiv, canvasWidth, canvasHeight)
{
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);

context = canvas.getContext("2d");
canvas.width = canvas.width;//clears canvas
loadImage("cat");
};

function loadImage(name)
{
image = new Image();
image.src = "images/cat" + currentFrame +".png";
draw("one");
if (currentFrame == 3 && total == 1){
setInterval(finaldraw,110);
}
};

function draw(params)
{
image.onload = function(){
canvas.width = canvas.width;
context.drawImage(image,0,0);
currentFrame++;
if (currentFrame == 4) {
currentFrame = 0;
total++;
};
}
};

function finaldraw(){
document.getElementById("canvas").removeEventListener("click",function(){});
image.src = "images/eatsheet.png";
image.onload = function(){
context.drawImage(image,350*finalFrame,0,width,350,0,0,width,350);
if (finalFrame == frames) {
finalFrame = 0;
} else {
finalFrame = finalFrame + 1;
}
}
};

最佳答案

您需要删除添加监听器时使用的完全相同的函数对象实例。函数表达式的计算结果为一个新的函数对象,并且与最初注册的对象不匹配,即使它具有完全相同的内容(在您的情况下不是...)

解决方案是拥有一个命名函数或一个分配有函数值的变量,并在添加和删除调用中使用相同的标识符。

关于javascript - 禁用点击 EventListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com