Я делаю веб-сайт для школьного проекта и хочу реализовать игру на javascript, я довольно далеко ушел, прежде чем столкнулся с этой ошибкой. большинство ошибок я смог исправить, но эту - нет. Мой учитель тоже не знает ответа, поэтому я надеюсь, что смогу найти здесь помощь
вот мой код
var player;
function startgame() {
gamearea.start();
playerupdater();
player = new component(30, 30, "blue", 10, 120);
}
var gamearea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateplayer, 50);
},
clear : function(){
console.info(this)
59------> this.canvas.clearRect(0, 0, this.canvas.width, this.canvas.height); <-
}
}
function playerupdatetimeout(){
setTimeout(playerupdater, 25)
}
function playerupdater(){
setInterval(gamearea.clear, 50);
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedx = 0;
this.speedy = 1;
this.x = x;
this.y = y;
this.update = function(){
ctx = gamearea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newpos = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}
function updateplayer(){
player.update();
}
function movup(){
player.speedy -=1;
}
function movdown(){
player.speedy +=1;
}
function movright(){
player.speedx -=1;
}
function movleft(){
player.speedx +=1;
}
консоль сообщает об ошибке в строке 59 (что указано в самом коде)
if you want to see the error yourself my website is online right here: https://jessep2000.github.io./home.html
and all my code used for this page is in this repository
https://github.com/Jessep2000/Jessep2000.github.io/tree/master
надеюсь, кто-то знает ответ, заранее спасибо!
Спасибо! Ошибка исчезла, но теперь консоль выдает следующую ошибку: «Uncaught TypeError: this.canvas.clearRect не является функцией в Object.clear (home.html: 59)»



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


В строке 59 this.canavas не определен, потому что вы пытаетесь получить доступ к ключу объекта из того же объекта. Создайте другой объект, например: -
let obj = {
clear : function(){
this.gamearea.canavas.clearRect(0, 0, this.canvas.width, this.canvas.height); <-
}
}
Если вы хотите использовать функцию очистки, просто используйте:
obj.clear()
Спасибо Роланд Старке и Шивендра Гупта за решение моей проблемы, вот конечный результат:
var player;
function startgame() {
gamearea.start();
playerupdater();
player = new component(30, 30, "blue", 10, 120);
}
let obj = {
clear : function(){
this.gamearea.canvas.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
var gamearea = {
canvas: document.createElement("canvas"),
start: function () {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateplayer, 50);
},
clear: function() {
let ctx = this.canvas.getContext("2d")
ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
}
}
function playerupdatetimeout(){
setTimeout(playerupdater, 25)
}
function playerupdater(){
setInterval(gamearea.clear.bind(gamearea), 50);
}
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.speedx = 0;
this.speedy = 1;
this.x = x;
this.y = y;
this.update = function(){
ctx = gamearea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newpos = function(){
this.x += this.speedx;
this.y += this.speedy;
}
}
function updateplayer(){
player.update();
}
function movup(){
player.speedy -=1;
}
function movdown(){
player.speedy +=1;
}
function movright(){
player.speedx -=1;
}
function movleft(){
player.speedx +=1;
}
Сейчас я работаю над установкой тайминга для функции очистки и обновления плеера. Спасибо, ребята, за помощь!
setInterval(gamearea.clear, 50);изменяет значениеthisвнутри функции очистки, вы можете исправить это, написавsetInterval(gamearea.clear.bind(gamearea), 50);