ES6 class methods not a function - javascript

I'm messing around with Javascript "classes" and I have a paddle that has a proper method to draw, but for some reason my moveBall function is messed up. Could anyone point out why? I get an error saying that moveBall() is not a function.
Edit: I included some more code, I call init() to start it all.
class Ball {
constructor(x, y, r, sAngle, rAngle) {
this.x = x;
this.y = y;
this.r = r;
this.sAngle = sAngle;
this.rAngle = rAngle;
this.speed = null;
}
drawBall() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, this.sAngle, this.rAngle);
ctx.fillStyle = "#FF0000";
ctx.fill();
}
moveBall() {
this.x += this.speed;
}
}
function init() {
var ball = new Ball(c.height / 2, c.width / 2, 10, 0, 2 * Math.PI);
var paddleLeft = new Paddle(0, 0, 20, 100);
ball.ballPhysics = 1.0;
draw(ball, paddleLeft);
main(ball);
}
window.main = function (ball) {
window.requestAnimationFrame(main);
ball.moveBall();
window.onload = function () {
document.addEventListener('keydown', function (event) {
if (event.keyCode === 65) {
}
}, false);
}
};

If you are using it like Ball.moveBall() than it's incorrect, you must instantiate Ball class first or use static methods like
class A {
static f() {
}
}
and call like
A.f();
otherwise check the snippet below
class Ball {
constructor(x, y, r, sAngle, rAngle) {
this.x = x;
this.y = y;
this.r = r;
this.sAngle = sAngle;
this.rAngle = rAngle;
this.speed = null;
}
drawBall() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, this.sAngle, this.rAngle);
ctx.fillStyle = "#FF0000";
ctx.fill();
}
moveBall() {
this.x += this.speed;
}
}
var greenBall = new Ball(0, 0 , 10, 0, 0);
greenBall.speed = 5;
greenBall.moveBall();
document.write(greenBall.x);

make sure you have an instance of ball in the scope of the code you are trying to run, and try var moveball = function(){this.x += this.speed; }; to see if it's a compile issue, and make sure you are accessing it like ball.moveball()

You define main to accept an argument ball. But you are never calling main, so you cannot pass an argument to it.
While window.requestAnimationFrame(main); will call the function, it won't pass anything to it.
It seems you want to refer to the ball variable that is defined inside init. In that case, remove the parameter ball from the function definition so that it doesn't shadow that variable:
window.main = function() { ... };
You also don't want to assign to window.onload inside main, because that wouldn't happen over and over again.

Related

"OOP" in canvas correct way

I'm trying to draw something on canvas with sugar code that we received not that long time ago. I'm using babel of course. I have two questions. First of all you can find my code below:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fillStyle = "#000";
ctx.fill();
ctx.closePath();
};
move() {
document.addEventListener('keydown', event => {
if (event.keyCode === 37) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.x--
this.draw();
}
if (event.keyCode === 39) {
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.x++
this.draw();
}
})
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
};
}
const rect = new Rectangle(130, 50);
const ball = new Ball(60, 40)
setInterval(() => {
rect.draw();
rect.move();
ball.draw();
}, 100);
I made two classes. One is rectangle, second ball. Rectangle is the one that can move with arrows. When i move, ball disapears for a brief second, then appears on the screen again. What am i doing wrong in this case? How game flow should look like properly?
Second question is: how can i make these two classes interract with each other? For example, i want that when rectangle will touch ball simple console.log will apear. Thanks
Most of the code is yours. Since I prefer using requestAnimationFrame I'm adding an identifier for the request: let requestId = null;.
The move() method of the rectangle deals only with the value of x, and takes the key as an attribute.
Also I've written the frame function that builds your animation frame by frame.
function frame() {
requestId = window.requestAnimationFrame(frame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect.move(key);
rect.draw();
ball.draw();
}
On keydown you change the value for the key variable, you cancel the current animation, and you call the frame function to start a new animation.
I've added as well a keyup event to stop the animation on key up.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
let key;
let requestId = null;
class Rectangle {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.rect(this.x, this.y, 50, 50);
ctx.fillStyle = "#000";
ctx.fill();
//ctx.closePath();
}
move(key) {
if (key == 37) {
this.x--;
}
if (key == 39) {
this.x++;
}
}
}
class Ball {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
//ctx.closePath();
}
}
const rect = new Rectangle(130, 50);
const ball = new Ball(60, 40);
rect.draw();
ball.draw();
function frame() {
requestId = window.requestAnimationFrame(frame);
ctx.clearRect(0, 0, canvas.width, canvas.height);
rect.move(key);
rect.draw();
ball.draw();
}
document.addEventListener("keydown", event => {
if (requestId) {
window.cancelAnimationFrame(requestId);
}
key = event.keyCode;
frame();
});
document.addEventListener("keyup", event => {
if (requestId) {
window.cancelAnimationFrame(requestId);
}
});
canvas{border:1px solid;}
<canvas id="myCanvas"></canvas>
PS: Please read this article requestAnimationFrame for Smart Animating

How to call class function in JavaScript?

New to JavaScript so might be something simple.
Getting an Error:
ball.html:46 Uncaught SyntaxError: Unexpected identifier
Why this is happening? I am new to JavaScript. But I tried everything in my knowledge to fix it. Tried removing the function but then it gives error:
draw() function is not defined in repeatMe() function.
HTML and JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style type="text/css">
body {
background-color: white;
}
canvas {
border: 3px solid black;
}
</style>
</head>
<body>
<canvas id="canvas-for-ball" height="800px" width="800px"></canvas>
<script type="text/javascript">
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
// The vertical location of the ball.
var y = 10;
var x = 10;
var ballRadius = 3;
var ySpeed = 1;
class Ball {
constructor(x, y, ballRadius, ySpeed) {
this.x = x;
this.y = y
this.ballRadius = BallRadius;
this.ySpeed = ySpeed;
}//endConstructor
function drawball() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
ctx.stroke();
}//endDrawball
function draw() {
ctx.clearRect(1, 1, 800, 800);
drawball();
}//endDraw
function move() {
// Update the y location.
y += ySpeed;
console.log(y);
}
} //endBall
// A function to repeat every time the animation loops.
function repeatme() {
// Draw the ball (stroked, not filled).
draw();
move();
//catch ball at bottom
if (y == 800)
{
ySpeed = 0;
}
window.requestAnimationFrame(repeatme);
}
// Get the animation going.
repeatme();
</script>
</body>
</html>
You need to see this before jumping into using JavaScript.Classes in JavaScript and few basics of programing in OOPS.
The issue you are facing is calling a function which doesn't exist. Also you have created class wrongly, this is not how functions are created in class in JavaScript.
Also you can't access class function directly, that's why they are in class. Need to create object of that class and that object will be used to call class function.
Change to this:
class Ball {
constructor(x, y, ballRadius, ySpeed) {
this.x = x;
this.y = y
this.ballRadius = BallRadius;
this.ySpeed = ySpeed;
}//endConstructor
drawball() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
ctx.stroke();
}//endDrawball
draw() {
ctx.clearRect(1, 1, 800, 800);
drawball();
}//endDraw
move() {
// Update the y location.
y += ySpeed;
console.log(y);
}
} //endBall
let Ball = new Ball(x, y, ballRadius, ySpeed);
// Note this is constructor calling so pass value for these arguments here
// A function to repeat every time the animation loops.
function repeatme() {
// Draw the ball (stroked, not filled).
Ball.draw();
Ball.move();
//catch ball at bottom
if (Ball.y == 800)
{
Ball.ySpeed = 0;
}
window.requestAnimationFrame(repeatme);
}
Would highly recommend to read few docs before jumping into JavaScript, as it's get confusing with callsbacks, promises, closures, hoisting and many more.
There is a problem here in that you're attempting to invoke some functions which don't exist:
function repeatme() {
// Draw the ball (stroked, not filled).
draw(); //<-- Where is this function?
move(); //<-- Where is this function?
//catch ball at bottom
if (y == 800)
{
ySpeed = 0;
}
window.requestAnimationFrame(repeatme);
}
I presume you want to use the functions which are part of the ball class. If so, you need to spin off a new instance of a Ball, and access the functions from there...:
function repeatme() {
// Draw the ball (stroked, not filled).
let ball = new Ball(x, y, ballRadius, ySpeed); //<--- create a new ball instance
ball.draw(); //<-- invoke the function which resides on a ball
ball.move(); //<-- invoke the function which resides on a ball
//catch ball at bottom
if (y == 800)
{
ySpeed = 0;
}
window.requestAnimationFrame(repeatme);
}
That "might" fix your code, but there is also a lot of other concepts happening here that you need to research. For example, you have some variables scoped OUTSIDE the context of a Ball, yet inside your Ball class, you are referencing them. Thus, you've essentially created a closure here... probably by accident.
You ought to just let the Ball do it's thing, without all these scoped variables... sort've like so:
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
//< -- Notice I removes these vars here, since we really just want to feed those into the constructor of a Ball...
class Ball {
constructor(x, y, ballRadius, ySpeed) {
this.x = x;
this.y = y
this.ballRadius = ballRadius;
this.ySpeed = ySpeed;
}//endConstructor
drawball() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.ballRadius, 0, 2 * Math.PI);
ctx.stroke();
}//endDrawball
draw() {
ctx.clearRect(1, 1, 800, 800);
this.drawball();
}//endDraw
move() {
// Update the y location.
this.y += this.ySpeed;
console.log(this.y);
}
} //endBall
// A function to repeat every time the animation loops.
function repeatme() {
// Draw the ball (stroked, not filled).
// The vertical location of the ball. Remember the variables above? Now the values are fed into here instead...
let ball = new Ball(10, 10, 3, 1)
ball.draw();
ball.move();
//catch ball at bottom
if (ball.y == 800)
{
ball.ySpeed = 0;
}
window.requestAnimationFrame(repeatme);
}
// Get the animation going.
repeatme();
I just defined below functions out of class()
function drawball() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
ctx.stroke();
}//endDrawball
function draw() {
ctx.clearRect(1, 1, 800, 800);
drawball();
}//endDraw
function move() {
// Update the y location.
y += ySpeed;
console.log(y);
}
Updated working code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
<style type="text/css">
body {
background-color: white;
}
canvas {
border: 3px solid black;
}
</style>
</head>
<body>
<canvas id="canvas-for-ball" height="800px" width="800px"></canvas>
<script type="text/javascript">
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
// The vertical location of the ball.
var y = 10;
var x = 10;
var ballRadius = 3;
var ySpeed = 1;
class Ball {
constructor(x, y, ballRadius, ySpeed) {
this.x = x;
this.y = y
this.ballRadius = BallRadius;
this.ySpeed = ySpeed;
}//endConstructor
} //endBall
function drawball() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, 2 * Math.PI);
ctx.stroke();
}//endDrawball
function draw() {
ctx.clearRect(1, 1, 800, 800);
drawball();
}//endDraw
function move() {
// Update the y location.
y += ySpeed;
console.log(y);
}
// A function to repeat every time the animation loops.
function repeatme() {
// Draw the ball (stroked, not filled).
draw();
move();
//catch ball at bottom
if (y == 800)
{
ySpeed = 0;
}
window.requestAnimationFrame(repeatme);
}
// Get the animation going.
repeatme();
</script>
</body>
</html>
The root of the issue is that you are creating a class but then never creating an instance of that class to call your functions on. Here is a cleaned up functioning example with comments explaining what things are doing differently.
// Gets a handle to the element with id canvasOne.
var canvas = document.getElementById("canvas-for-ball");
// Get a 2D context for the canvas.
var ctx = canvas.getContext("2d");
// The vertical location of the ball.
var y = 10;
var x = 10;
var ballRadius = 3;
var ySpeed = 1;
class Ball {
constructor(x, y, ballRadius, ySpeed) {
// changed these to set the private members
this._x = x;
this._y = y
// updated the assignment here, it had the wrong case
this._ballRadius = ballRadius;
this._ySpeed = ySpeed;
} //endConstructor
// added a setter for ySpeed so you can acess it outside of the class
set VerticleSpeed(val){
this._ySpeed = val;
}
// added a getter/setter for y so you can access it outside of the class
get VerticlePosition(){
return this._y;
}
// remove the function keyword, it's not needed
drawball() {
ctx.beginPath();
// updated this to reference the properties on the class
ctx.arc(this._x, this._y, this._ballRadius, 0, 2 * Math.PI);
ctx.stroke();
} //endDrawball
// remove the function keyword, it's not needed
draw() {
ctx.clearRect(1, 1, 800, 800);
this.drawball();
} //endDraw
// remove the function keyword, it's not needed
move() {
// Update the y location.
// updated this to reference the properties on the class
this._y += this._ySpeed;
console.log("Ball position", this._y);
}
} //endBall
// A function to repeat every time the animation loops.
function repeatme() {
// Draw the ball (stroked, not filled).
// upated to call the functions on the instance of the class
myBall.draw();
myBall.move();
//catch ball at bottom
// changed to check the property on the instance of the class
// changed this bit to make it bounce and if its outside the bounds, this is just me showing off and having fun with this example
if (myBall.VerticlePosition >= canvas.height) {
// changed to assign the property on the instance of the class
myBall.VerticleSpeed = -ySpeed;
} else if (myBall.VerticlePosition <= 0){
myBall.VerticleSpeed = ySpeed;
}
window.requestAnimationFrame(repeatme);
}
// create an instance of your class
let myBall = new Ball(x, y, ballRadius, ySpeed)
// Get the animation going.
repeatme();
body {
background-color: white;
}
canvas {
border: 3px solid black;
}
.as-console-wrapper {
max-height: 25px !important;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<canvas id="canvas-for-ball" height="150px" width="400px"></canvas>
</body>
</html>

Canvas: X value changing in console but not in canvas

I am pulling coordinates from an API and setting them to a class of Rectangle. When looping through the data array, I am able to create each rectangle, but when it comes to moving them, that is where I am having trouble.
The x coordinates are changing in the console at the setInterval of move(), but the squares themselves are not moving across the screen.
When I have c.clearRect(0,0,innerWidth, innerHeight); in move(), all of the rectangles disappear. Without it, they do not move at all.
if(this % 6 === 0){
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
is referring to the data array and if the index is divisible by 6, make that square black. Although, in this context, it is not working.
Here is my code:
<script>
const canvas = document.getElementById("canvas");
const c = canvas.getContext('2d');
let xhReq = new XMLHttpRequest();
xhReq.open("GET", "(api here)", false);
xhReq.send(null);
const data = JSON.parse(xhReq.responseText);
class Rectangle {
constructor(x, y, w, h, vx, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = vx;
this.color = color;
}
draw() {
c.fillRect(this.x, this.y, this.w, this.h);
if(this % 6 === 0){
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
}
}
move(){
c.clearRect(0,0,innerWidth, innerHeight);
if (this.x > 800 || this.x < 0){
this.vx = -this.vx;
}
this.x+= this.vx;
c.beginPath();
console.log("here is the x value:" + this.x);
}
}
for(let i=0; i<data.length; i++){
let info = data[i]
let rec = new Rectangle(info.x, info.y, info.w, info.h, info.vx, info.color);
rec.draw();
setInterval(function() {
rec.move();
}, 50);
}
</script>
There are a lot of issues with your code.
You are only updating the position and not making the draw call again.
Move the rec.draw() call inside your setInterval. Remember, ordering is important. Ideally, you should update() first and draw() later.
setInterval(function() {
rec.move();
rec.draw();
}, 50);
Also, remove these lines from the move() function as you don't want to clear the canvas every time you update the variables. Clear the canvas in the beginning of the draw() function. Plus, since you're dealing with fillRect(), you dont need to include beginPath()
c.clearRect(0,0,innerWidth, innerHeight);
...
c.beginPath();
You first need to specify the fillStyle then proceed with drawing the rectangle using fillRect(), not the other way round. The draw() function should look like this:
draw() {
c.clearRect(0, 0, innerWidth, innerHeight);
if(this % 6 === 0){ // <-- Not really sure what is going on here
c.fillStyle = "#000";
} else {
c.fillStyle = "" + this.color + "";
}
c.fillRect(this.x, this.y, this.w, this.h);
}
In the code block in point number #3 you are using the Modulus Operator % on the the instance of the class itself i.e. this and not a number. I'm assuming you want something like this.x in there.
Apart from the points above there are still a handful of issues with your code. But it's outside the context of this question.
Edited for a final solution below:
const canvas = document.getElementById("canvas");
const context = canvas.getContext('2d');
const xhr = new XMLHttpRequest();
// Usng var as we are making an async request and need to update this variable
var data = null;
// An empty array to store our rectangles
var collection = [];
// Using an asyn request as we don't necessarily need to wait for this step
xhr.open('GET', '<api>', true)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
data = JSON.parse(xhr.responseText);
dataLoaded();
} else {
// The request gave an error response
}
}
};
xhr.send();
function dataLoaded(){
for(let i = 0; i < data.length; i++){
let info = data[i];
collection.push(new Rectangle(info.x, info.y, info.w, info.h, info.vx, info.color));
}
setInterval(animate, 50);
}
function animate(){
context.clearRect(0, 0, canvas.width, canvas.height);
for(let i = 0; i < collection.length; i++){
let rect = collection[i];
rect.update();
rect.draw();
}
}
class Rectangle {
constructor(x, y, w, h, vx, color){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.vx = vx;
this.color = color;
}
update(){
if (this.x > 800 || this.x < 0){
this.vx = -this.vx;
}
this.x += this.vx;
}
draw(){
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.w, this.h);
}
}

Uncaught TypeError: rectangle.draw is not a function

So, I've been working on a small project which draws two rectangles that will keep on bouncing to each side of a canvas in which they're drawn. Now, that part worked but i had some really messy coding so i decided to approach it from a different angle and now I'm getting Uncaught TypeError: rectangle.draw is not a funtion.
I don't understand what causes this error of how to solve it, so help would be appreciated.
Rectangle:
function Rectangle(width, height, posX, posY, speedX, speedY, color)
{
this.width = width;
this.height = height;
this.posX = posX;
this.posY = posY;
this.speedX = speedX;
this.speedY = speedY;
this.color = color;
function move(){
this.posX += this.speedX;
this.posY += this.speedY;
}
function changeX(){
this.speedX = -this.speedX;
}
function changeY(){
this.speedY = -this.speedY;
}
function draw()
{
if (gameArea != null){
gameArea.fillStyle = this.color;
gameArea.fillRect(this.posX, this.posY, this.speedX, this.speedY);
}
}
function getTop(){
return this.posY;
}
function getRight(){
return this.posX + this.width;
}
function getBottom(){
return this.posY + this.height;
}
function getLeft(){
return this.posX;
}
}
main (executed after page is loaded):
function main()
{
createRectangles();
var c = document.getElementById("myCanvas");
gameArea = c.getContext("2d");
rect1.draw();
rect2.draw();
pauseButton = document.getElementById("pause");
pauseButton.addEventListener("click",pause);
document.getElementById("reset").addEventListener("click",reset);
}
and createRectangles:
function createRectangles()
{
rect1 = new Rectangle(50,100,getRandomX(0),getRandomY(),getRandomSpeed(),getRandomSpeed(), "#FF0000");
rect2 = new Rectangle(50,100,getRandomX(400),getRandomY(),getRandomSpeed(),getRandomSpeed(), "#0000FF");
}
the exact error I'm getting is Uncaught TypeError: rect1.draw is not a function
Since you are creating objects using a function constructor, you need to declare the inner methods on that object, not just have them exist within the function.
Meaning, instead of saying:
function Rectangle(width, height, posX, posY, speedX, speedY, color)
{
// ...
function draw() // <--- This is just a function within a function
{
if (gameArea != null){
gameArea.fillStyle = this.color;
gameArea.fillRect(this.posX, this.posY, this.speedX, this.speedY);
}
}
// ...
You attach that function (using this) to the object that is created when using a function constructor:
function Rectangle(width, height, posX, posY, speedX, speedY, color)
{
// ...
this.draw = function() // <--- This adds the function as a method to any object you instantiate using new Rectagle()
{
if (gameArea != null){
gameArea.fillStyle = this.color;
gameArea.fillRect(this.posX, this.posY, this.speedX, this.speedY);
}
}
// ...
NOTE:
You need to do this for all methods you want to exist on the instantiated object.

Which was is it to best declare a property in JavaScript?

If you are building a function type class in JavaScript when you declare a variable is it better to do it with
var this.variableName = variableName
var this.x = x
or is it better to just do it like this.
this.x
I tried using the var and it gave an error in Google debuger. Why would this be the case or are properties different than a variable that is set in a function "object".
Code:
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
this.draw = function(context){
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}
}
When an object is declared, it is already declared, so doing something like this is, not only illegal, but also redundant.
// DON'T DO THIS!!!
var this.a = 'a'; // NO!!!!!!!!!
Instead, just declare your object and then just append things to that object, since it's already initialized
var obj = {};
obj.a = 'a';
obj.b = 'b';
The problem you'll probably face when declaring a function in your object is a matter of scope and how this works in Javascript.
For this, you have a couple of alternatives:
Declare a that variable that you can then use in your function:
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
var that = this;
this.draw = function(context){
// this refers to the global object (window)
// that refers to your Circle Object
context.beginPath();
context.arc(that.x, that.y, that.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}
}
If you're using an ECMAScript 5 supported browser (not IE8), you can bind the function to your Circle object.
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
this.draw = function(context){
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}.bind(this);
}
If you want to support IE8 and use .bind, you can just use underscore.js and use the _.bind function.
function Circle(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
// I've added the drawing code to the actual circle
// they can draw themselves.
this.draw = _.bind(function(context){
context.beginPath();
context.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
context.closePath();
context.fill();
}, this);
}

Categories

Resources