gpt4 book ai didi

javascript - 错误: Uncaught TypeError: this.绘制不是函数

转载 作者:行者123 更新时间:2023-12-02 14:17:27 27 4
gpt4 key购买 nike

我有这个 JavaScript 代码,我用它在 Canvas 对象上绘制一个小正方形,并使其向左或向右移动,但我收到此错误,但我不知道为什么。

function Walker(canvas, ctx) {
console.log("Received canvas with (" + canvas.width + ", " + canvas.height + ")");

this.x = Math.floor((Math.random() * canvas.width) + 1);
this.y = Math.floor((Math.random() * canvas.height) + 1);
this.canvas = canvas;
this.ctx = ctx;

this.draw = function(x = this.x, y = this.y) {
console.log("Drawing at (" + this.x + ", " + this.y + ")");

this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.rect(this.x, this.y, 5, 5);
this.ctx.fillStyle = "#000000";
this.ctx.fill();
this.ctx.closePath();
};

this.walk = function() {
left_or_right = Math.floor(Math.random() * 2);

if(left_or_right === 0) {
console.log("Moving right");
this.x += 1;
}
else {
console.log("Moving left");
this.x -= 1;
}

this.draw(this.x, this.y);
};

}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var w = new Walker(canvas, ctx);

w.draw();
setInterval(w.walk, 10000);

这是我的 .html 文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gamedev Canvas Workshop</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script src="../scripts/walk.js" type="text/javascript"></script>
</body>
</html>

这段代码有什么问题?

最佳答案

查看您的代码。问题就在这里

setInterval(function(){
w.walk();
}, 10000);

当您将 w.walk 作为参数传递时,它会从对象中获取函数。如果函数被获取,它就会丢失它的上下文。所以在w.walk 的 this 副本不是您的 w。在这种情况下,您有多种变体可以实现您的目标。

1) 您可以使用像我的代码中那样的包装函数。
2) 您可以使用 bind 函数 - setInterval(w.walk.bind(w), 1000 }

function Walker(canvas, ctx) {
console.log("Received canvas with (" + canvas.width + ", " + canvas.height + ")");

this.x = Math.floor((Math.random() * canvas.width) + 1);
this.y = Math.floor((Math.random() * canvas.height) + 1);
this.canvas = canvas;
this.ctx = ctx;

this.draw = function(x = this.x, y = this.y) {
console.log("Drawing at (" + this.x + ", " + this.y + ")");

this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.beginPath();
this.ctx.rect(this.x, this.y, 5, 5);
this.ctx.fillStyle = "#000000";
this.ctx.fill();
this.ctx.closePath();
};

this.walk = function() {
left_or_right = Math.floor(Math.random() * 2);

if(left_or_right === 0) {
console.log("Moving right");
this.x += 1;
}
else {
console.log("Moving left");
this.x -= 1;
}

this.draw(this.x, this.y);
};

}

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var w = new Walker(canvas, ctx);

w.draw();
setInterval(function(){
w.walk();
}, 10000);
<canvas id='myCanvas'></canvas>

关于javascript - 错误: Uncaught TypeError: this.绘制不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38913731/

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