2016-08-12 3 views
0

У меня есть этот код javascript, который я использую, чтобы нарисовать маленький квадрат на холсте, и заставить его перемещаться влево или вправо, но я получаю эту ошибку и я не знаю почему.Ошибка: Uncaught TypeError: this.draw не является функцией

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> 

Что не так с этим кодом?

ответ

1

Смотрите ваши проблемы code.The здесь

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

Когда вы передаете w.walk в качестве параметра, он получает свою функцию от object.If функция getted из него теряет это context .so в Копия 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>

+0

я добавил свой .html файл. –

+0

Спасибо, ты спасатель жизни! –

Смежные вопросы