How to call class function in JavaScript? - 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>

Related

Why does my triangle on canvas have artifacts? [duplicate]

I'm doing a Pong game in javascript in order to learn making games, and I want to make it object oriented.
I can't get clearRect to work. All it does is draw a line that grows longer.
Here is the relevant code:
function Ball(){
this.radius = 5;
this.Y = 20;
this.X = 25;
this.draw = function() {
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
};
}
var ball = new Ball();
function draw(){
player.draw();
ball.draw();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
ball.X++;
}
I've tried to put the ctx.clearRect part in the draw() and ball.draw() functions and it doesn't work.
I also tried fillRect with white but it gives the same results.
How can I fix this?
Your real problem is you are not closing your circle's path.
Add ctx.beginPath() before you draw the circle.
jsFiddle.
Also, some tips...
Your assets should not be responsible for drawing themselves (their draw() method). Instead, perhaps define their visual properties (is it a circle? radius?) and let your main render function handle canvas specific drawing (this also has the advantage that you can switch your renderer to regular DOM elements or WebGL further down the track easily).
Instead of setInterval(), use requestAnimationFrame(). Support is not that great at the moment so you may want to shim its functionality with setInterval() or the recursive setTimeout() pattern.
Your clearRect() should be passed the dimensions from the canvas element (or have them defined somewhere). Including them in your rendering functions is akin to magic numbers and could lead to a maintenance issue further down the track.
window.onload = function() {
var cvs = document.getElementById('canvas');
var ctx = cvs.getContext('2d');
var cvsW = cvs.Width;
var cvsH = cvs.Height;
var snakeW = 10;
var snakeH = 10;
function drawSnake(x, y) {
ctx.fillStyle = '#FFF';
ctx.fillRect(x*snakeW, y * snakeH, snakeW, snakeH);
ctx.fillStyle = '#000';
ctx.strokeRect(x*snakeW, y * snakeH, snakeW, snakeH);
}
// drawSnake(4, 5)
//create our snake object, it will contain 4 cells in default
var len = 4;
var snake = [];
for(var i = len -1; i >=0; i--) {
snake.push(
{
x: i,
y: 0
}
)
};
function draw() {
ctx.clearRect(0, 0, cvsW, cvsH)
for(var i = 0; i < snake.length; i++) {
var x = snake[i].x;
var y = snake[i].y;
drawSnake(x, y)
}
//snake head
var snakeX = snake[0].x;
var snakeY = snake[0].y;
//remove to last entry (the snake Tail);
snake.pop();
// //create a new head, based on the previous head and the direction;
snakeX++;
let newHead = {
x: snakeX,
y: snakeY
}
snake.unshift(newHead)
}
setInterval(draw, 60);
}
my clearRect is not working, what's the problem and solution?

What is the best way to remove/delete a function object once instantiated/drawn to canvas?

The snippet code below shows a single function object called "Circle" being drawn to a canvas element. I know how to remove the visual aspect of the circle from the screen. I can simply change its opacity over time with c.globalAlpha=0.0; based on event.listener 's or 'object collision', However if I visually undraw said circle; it still is there and being computed on, its still taking up browser resources as it invisibly bounces to and fro on my canvas element.
So my question is: What is the best way to remove/delete a function object once instantiated/drawn to canvas? =>(so that it is truly removed and not invisibly bouncing in the browser)
let canvas = document.getElementById('myCanvas');
let c = canvas.getContext('2d');
function Circle(x, y, arc, dx, dy, radius){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.arc = arc;
this.cCnt = 0;
this.radius = radius;
this.draw = function() {
c.beginPath();
//context.arc(x,y,r,sAngle,eAngle,counterclockwise);
c.arc(this.x, this.y, this.radius, this.arc, Math.PI * 2, false); //
c.globalAlpha=1;
c.strokeStyle = 'pink';
c.stroke();
}
this.update = function() {
if (this.x + this.radius > canvas.width || this.x - this.radius < 0){
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < 0){
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
this.draw();
}
}
var circle = new Circle(2, 2, 0, 1, 1, 2); // x, y, arc, xVel, yVel, radius
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height)
circle.update();
}
animate();
body {
background-color: black;
margin: 0;
}
<canvas id="myCanvas" width="200" height="60" style="background-color: white">
A lot of canvas libraries solve this problem by keeping an array of objects that are in the canvas scene. Every time the animate() function is called, it loops through the list of objects and calls update() for each one (I'm using the names you're using for simplicity).
This allows you to control what is in the scene by adding or removing objects from the array. Once objects are removed from the array, they will no longer be updated (and will get trash collected if there are no other references hanging around).
Here's an example:
const sceneObjects = [];
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, canvas.width, canvas.height);
// Update every object in the scene
sceneObjects.forEach(obj => obj.update());
}
// Elsewhere...
function foo() {
// Remove an object
sceneObjects.pop();
// Add a different object
sceneObjects.push(new Circle(2, 2, 0, 1, 1, 2));
}
It's not uncommon to take this a step further by creating a Scene or Canvas class/object that keeps the list of scene objects and gives an interface for other parts of the program to use (for example, Scene.add(myNewCircle) or Scene.remove(myOldCircle)).

Canvas: Strange behavior when pressing key down

By default the rectangle of my canvas should move from left to right. When pressing the key down, it should start moving down.
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0;
function draw(x_move, y_move) {
requestAnimationFrame(function() {
draw(x_move, y_move);
});
ctx.beginPath();
ctx.rect(x, y, 20, 20);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.closePath();
x = x + x_move;
y = y + y_move;
}
draw(1, 0);
document.addEventListener('keydown', function(event) {
//console.log(event.keyCode);
if (event.keyCode == 40) {
draw(0, 1);
}
});
canvas { background-color: red; }
<canvas id="canvas" width="600" height="400"></canvas>
Using the code above, you may at least notice two issues:
When pressing key down, the rectangle moves down but also keeps moving to the right.
When you keep pressing the down key multiple times, the speed gets increased.
How can I fix those issues?
See where you call
requestAnimationFrame(function() {
draw(x_move, y_move);
});
You're now recursively calling draw().
Now every time you call draw(), it gets called over and over and over again. And when you call it from the keydown event, you call it 2x as often, then 3x as often on the second time you press it, etc.
I'm not entirely clear on what your objective is here, but if you wanted to just adjust the trajectory of the square by pressing down, you could do something like this:
document.addEventListener('keydown', function(event) {
//console.log(event.keyCode);
if (event.keyCode == 40) {
adjustDownwardTrajectory();
}
});
and have that adjustDownwardTrajectory() change some downwardTrajectory variable such that:
function draw(x_move, y_move) {
requestAnimationFrame(function() {
draw(x_move, y_move);
});
ctx.beginPath();
ctx.rect(x, y, 20, 20);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.closePath();
x = x + x_move;
y = y + y_move + downwardTrajectory;
}
I believe this is what you want to be doing (and you were close!). I hope this is the behaviour you were looking for.
A related point: It may be a good idea to wrap x_move and y_move up in a closure with these functions so you avoid accidentally changing them in other parts of the program. That way the functions you implement for changing directions of the square will have private access to these variables.
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
x = 0,
y = 0;
var x_move = 1;
var y_move = 0;
function draw() {
requestAnimationFrame(function() {
draw();
});
ctx.beginPath();
ctx.rect(x, y, 20, 20);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#ffffff";
ctx.fill();
ctx.closePath();
x = x + x_move;
y = y + y_move;
}
draw();
document.addEventListener('keydown', function(event) {
//console.log(event.keyCode);
if (event.keyCode == 40) {
x_move = 0;
y_move = 1;
}
});
canvas {
background-color: red;
}
<canvas id="canvas" width="600" height="400"></canvas>
keyboardEvent.keyCode is a depreciated property. You should use keyboardEvent.code or keyboardEvent.key they provided a named key which is much easier to manage than trying to remember key codes.
You can use fillRect rather than rect and you don't need to use beginPath and fill. You don't need to use closePath you only use it if you want to close a shape (ie add a line from the last point to the first) rect is already closed
You can set the callback directly as the argument for requestAnimationFrame
It pays to group related data together. In this case the square has a position x, y and a delta position (x_move, y_move) that are better off in a object. A good clue that you have related data is when you find yourself adding the same name to a set of variables. Objects can also include behaviour in the form of functions like draw and update
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// list of named keys to record state of
const keys = {
ArrowDown: false,
};
// create key event listeners
document.addEventListener('keydown', keyEvent);
document.addEventListener('keyup', keyEvent);
// define the square
const square = {
x : 0, // position
y : 0,
dx : 0, // delta pos
dy : 0,
draw () { // function to render the square
ctx.fillStyle = "#ffffff";
ctx.fillRect(this.x, this.y, 20, 20);
},
update () { // function to update square
if(keys.ArrowDown){
this.dx = 0;
this.dy = 1;
}else {
this.dx = 1;
this.dy = 0;
}
this.x += this.dx;
this.y += this.dy;
}
}
// main animation update function called once per frame 1/60th second
function update () {
requestAnimationFrame(update);
ctx.clearRect(0, 0, canvas.width, canvas.height);
square.update();
square.draw();
}
// key event records named key state (false up, true down)
function keyEvent (event) {
if(keys[event.code] !== undefined){
keys[event.code] = event.type === "keydown";
}
}

Trying to animate shapes in canvas, it shows up, but doesn't move

I'm trying to animate polygons made using lineTo in canvas. It shows up, but won't move. I tried to follow the object approach, but it didn't seem to do anything.
Help?
<!doctype html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
<script>
"use strict";
var canvas;
var ctx;
var timer;
var shapes;
var x;
var y;
function degreesToRadians(degrees) {
return (degrees*Math.PI)/180;
}
//to rotate stuff, not currently in use
function rotateStuff() {
roTimer = setInterval(ctx.rotate(degreesToRadians(60)),100);
}
//constructor for Shape object, not currently in use
function Shape() {
//this.x = canvas.width/2 + Math.random()*10-5;
//this.y = canvas.height/2 + Math.random()*10-5;
this.r = Math.random()*20-5;
this.vx = Math.random()*10-5;
this.vy = Math.random()*10-5;
var colors = ['red','green','orange','purple','blue','aqua','pink','gold'];
this.color = colors[Math.floor(Math.random()*colors.length)];
}
//pushes the shapes to an array, not currently in use
function makeShapes() {
shapes = [];
for (var i = 0; i<2; i++){
shapes.push(new Shape());
}
}
//fills and resets background
function fillBackground() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = 'lighter';
}
//draws the shape
function drawShapes(r, p, m) {
//canvas, x position, y position, radius, number of points, fraction of radius for inset
fillBackground();
x = 350;
y = 350;
r = Math.random()*20-5;
//for (var i = 0; i < shapes.length; i++) {
//var s = shapes[i];
ctx.save();
ctx.beginPath();
ctx.translate(x, y);
ctx.moveTo(0,0-r);
//}
for (var i2 = 0; i2 < p; i2++) {
ctx.rotate(Math.PI / p);
ctx.lineTo(0, 0 - (r*m));
ctx.rotate(Math.PI / p);
ctx.lineTo(0, 0 - r);
}
ctx.fillStyle = "yellow";
ctx.fill();
var vx = Math.random()*10-5;
var vy = Math.random()*10-5;
x += vx;
y += vy;
r -=8
ctx.restore();
}
//}
window.onload = function() {
canvas = document.getElementById('animCanvas');
ctx = canvas.getContext('2d');
//makeShapes();
//console.log(shapes);
timer = setInterval(drawShapes(40, 5, 0.5), 100);
//timer2 = setInterval(makeShapes, 4500);
}
</script>
</head>
<body>
<canvas width='700' height='700' id='animCanvas'></canvas>
</body>
</html>
A coding hint: Separate your code into discrete duties. This separation lets you concentrate your coding focus on simpler tasks. And once you've got that task running correctly you can move onto another task without worrying that a previous task has become broken.
Here are the tasks for your "rotate stars" project
1. Draw a star and
2. Rotate that star using animation.*
... and their descriptions
drawShapes() draws one star at a specified [x,y] position at a specified currentAngle
animate() runs an animation loop that:
Clears the canvas.
Fills the background.
Draws the star (or many stars) with `drawShapes`.
Changes the `currentAngle` rotation for the next loop.
Requests another animation loop.
About rotating
Rotating your shape is a simple 2 step process:
1. Move to the shape's centerpoint: `.translate(centerX,centerY)'
2. Rotate the canvas to the currently desired angle: `rotate(currentAngle)`
Since translate and rotate are not automatically undone, you must "clean up" after your transformations. An easy way to do that is to do this: context.setTransform(1,0,0,1,0,0). This sets the internal transformation matrix to its default state (==fully untransformed).
So your rotation process becomes:
1. Move to the shape's centerpoint: `.translate(centerX,centerY)'
2. Rotate the canvas to the currently desired angle: `.rotate(currentAngle)`
3. Reset the canvas: `.setTransform(1,0,0,1,0,0)`
Here's annotated code and a Demo:
var canvas;
var ctx;
canvas = document.getElementById('animCanvas');
ctx = canvas.getContext('2d');
var cw=canvas.width;
var ch=canvas.height;
var shapes=[];
var star1={ x:50, y:100, r:40, currentAngle:0, p:5, m:.5, fill:'yellow',angleChange:Math.PI/60}
var star2={ x:150, y:100, r:25, currentAngle:0, p:55, m:5, fill:'blue',angleChange:-Math.PI/360}
var star3={ x:250, y:100, r:25, currentAngle:0, p:15, m:3, fill:'red',angleChange:Math.PI/120}
requestAnimationFrame(animate);
function drawShapes(star) {
ctx.save();
// translate to the star's centerpoint
ctx.translate(star.x,star.y);
// rotate to the current angle
ctx.rotate(star.currentAngle)
// draw the star
ctx.beginPath();
ctx.moveTo(0,0-star.r);
for (var i2 = 0; i2 < star.p; i2++) {
ctx.rotate(Math.PI / star.p);
ctx.lineTo(0, 0 - (star.r*star.m));
ctx.rotate(Math.PI / star.p);
ctx.lineTo(0, 0 - star.r);
}
ctx.fillStyle =star.fill;
ctx.fill();
ctx.restore();
}
function fillBackground() {
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = 'rgba(0,0,0,0.3)';
ctx.fillRect(0,0,canvas.width,canvas.height);
ctx.globalCompositeOperation = 'lighter';
}
function animate(time){
// clear the canvas
ctx.clearRect(0,0,cw,ch);
// fill the background
fillBackground();
// draw the stars
// If you put star1,star2,star3 in a stars[] array then
// you could simply the following demo code by looping
// through the array
//
// draw the star1
drawShapes(star1);
// increase star1's current rotation angle
star1.currentAngle+=star1.angleChange;
// draw the star2
drawShapes(star2);
// increase star2's current rotation angle
star2.currentAngle+=star2.angleChange;
// draw the star3
drawShapes(star3);
// increase star3's current rotation angle
star3.currentAngle+=star2.angleChange;
// request another animation loop
requestAnimationFrame(animate);
}
<canvas width='700' height='700' id='animCanvas'></canvas> </body>

ES6 class methods not a function

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.

Categories

Resources