How to make a shape move with keyIsDown (p5.js) - javascript

So I'm trying to make a shape move in the canvas with p5.js. However, all it does is redrawing the same shape in the newly assigned position without deleting the shape in the old position, leaving sort of a trail, and not completely moving it like I wanted. You can see the result here.
Below is the code for my "Player" class (the shape that I want to move):
function Player() {
this.hp = 10;
this.x = 230;
this.y = 240;
this.color = "red";
this.r = 10;
this.spawn = function(){
fill(this.color);
noStroke();
rect(this.x, this.y, this.r*2, this.r*2);
}
}
This is my code in the setup and draw functions in p5.js:
var p1;
function setup() {
createCanvas(500, 500);
background("green");
p1 = new Player();;
}
function draw() {
p1.spawn();
if (keyIsDown(LEFT_ARROW)) {
p1.x--;
}
if (keyIsDown(RIGHT_ARROW)) {
p1.x++;
}
if (keyIsDown(UP_ARROW)) {
p1.y--;
}
if (keyIsDown(DOWN_ARROW)) {
p1.y++;
}
}
Any help would be greatly appreciated. Thanks!

You need to clear out old frames using the background() function. You should generally call background() from the first line in the draw() function. Here's an example:
function setup() {
createCanvas(200, 200);
}
function draw() {
background(64);
ellipse(mouseX, mouseY, 25, 25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/p5.min.js"></script>
Try moving the call to the background() function to the setup() function to see what I mean.

you just use
if (keyDown(the key you want to use)) {
}
or
if(keyDown("the key you want to use")){
}

Related

WEBGL P5js not showing image as texture

I'm trying to use an image as a texture for a plane in P5js using WEBGL, but for some reason it isn't working.
I've tried to get rid of all the lighting and just use ambientLight() but still it isn't showing. I've tried in a new sketch with just the plane and the same code and it works fine, so I don't understand what the problem is in this sketch?
let bodyShape;
let spacing = 50;
let bgTexture;
function preload() {
bodyShape = loadModel('Human_body_with_net.obj');
bgTexture = loadImage('assets/gormleyline.jpeg');
}
function setup() {
createCanvas(600, 600,WEBGL);
noStroke();
}
function draw() {
background(0);
debugMode();
orbitControl();
ambientLight(255);
// pointLight(102,0,0,0,1,0);
// pointLight(0,102,255,1,0,0);
// directionalLight(255,0,0,0,1,0);
// directionalLight(255,255,255,0,0,-1);
// pointLight(0,0,0,mouseX,mouseY,0);
backgroundShape();
push();
translate(-260,0,0);
for (let x = 0; x<10; x++){
bodyFunction(x+spacing,0,0);
rotateX(50);
}
pop();
}
function bodyFunction(x,y,z,rotation){
specularMaterial(255);
translate(x,y,z);
rotateX(HALF_PI);
model(bodyShape);
}
function backgroundShape(){
push();
translate(0,0,-130);
plane(600,600);
texture(bgTexture)
pop();
}
Here's the link to the sketch in case it's useful: https://editor.p5js.org/rociorey/sketches/4H1eFQpKh
Thank you!
You must specify the texture for the geometry before you draw the geometry (see texture()):
texture(bgTexture);
plane(600,600);

How to jump object using arrow key in p5js?

This is my code that I tried. The ball is jumping when I pressing "up arrow key" or "space bar".The problem is that I am unable to move ball little bit forward when ball jumped.Can anybody help me please?
let jumper;
function setup() {
createCanvas(400, 400);
jumper = new Jumper();
}
function draw() {
clear();
jumper.run();
push();
fill(217);
textFont('Avenir');
textAlign(CENTER,CENTER);
textSize(33);
text('space bar to jump', width>>1, height*0.15);
pop();
}
function keyPressed() {
jumper.vel.y = -4;
jumper.vel.x=+5;
}
I set up a very basic example of what I think you might be working towards:
let jumper;
function setup() {
createCanvas(400, 400);
jumper = new Jumper();
}
function draw() {
clear();
jumper.run();
push();
fill(217);
textFont('Avenir');
textAlign(CENTER,CENTER);
textSize(33);
text('space bar to jump', width>>1, height*0.15);
pop();
}
function keyPressed() {
jumper.x+=5;
}
class Jumper {
constructor() {
this.x = 10;
this.y = height/2;
}
run() {
ellipse(this.x, this.y, 10, 10);
}
}
<script src="https://cdn.jsdelivr.net/npm/p5#0.10.2/lib/p5.js"></script>
#Dishant was correct in that your code had a typo in where you did jumper.vel.x =+ 5 which is basically just setting the position of the jumper to the x position of 5. When what you want is to actually make the jumper move 5 pixels forward - in my example this done using jumper.x += 5 but you'd of course use jumper.vel.x += 5 as that code wasn't shown in your question!
You need to remove the bug in the second last line.
jumper.vel.x += 5;

How does the p5.js draw function work?

Can't work out what I'm doing wrong. Looking at the code below my logic is that each time the draw function is called the ellipse's coordinates are changed to be another random number.
However instead of the coordinates being changed, the ellipse is just being redrawn at the 'new' coordinates.
Does anyone care to shed some light on why the shape is being redrawn rather than moved? I'm using the p5 javascript library.
var frate = 10;
var elliX = 500;
var elliY = 400;
function setup() {
createCanvas(100, 100);
frameRate(frate);
}
function draw() {
elliX = (random(0,100));
elliY = (random(0,100));
ellipse(elliX, elliY, 30);
}
p5 doesn't clear the canvas by default, so it's adding a new circle every time you're drawing. To clear, you can call clear() beforehand, like so:
var frate = 10;
var elliX = 500;
var elliY = 400;
function setup() {
createCanvas(100, 100);
frameRate(frate);
}
function draw() {
clear();
elliX = (random(0,100));
elliY = (random(0,100));
ellipse(elliX, elliY, 30);
}
<script src="https://unpkg.com/p5#0.6.1/lib/p5.min.js"></script>

Make identical objects move independently in Javascript Canvas

So I am trying to make a simple space game. You will have a ship that moves left and right, and Asteroids will be generated above the top of the canvas at random X position and size and they will move down towards the ship.
How can I create Asteroid objects in seperate positions? Like having more than one existing in the canvas at once, without creating them as totally seperate objects with seperate variables?
This sets the variables I would like the asteroid to be created on.
var asteroids = {
size: Math.floor((Math.random() * 40) + 15),
startY: 100,
startX: Math.floor((Math.random() * canvas.width-200) + 200),
speed: 1
}
This is what I used to draw the asteroid. (It makes a hexagon shape with random size at a random x coordinate)
function drawasteroid() {
this.x = asteroids.startX;
this.y = 100;
this.size = asteroids.size;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo(this.x,this.y-this.size*0.5);
ctx.lineTo(this.x+this.size*0.9,this.y);
ctx.lineTo(this.x+this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x,this.y+this.size*1.5);
ctx.lineTo(this.x-this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x-this.size*0.9,this.y);
ctx.fill();
}
I included ALL of my code in this snippet. Upon running it, you will see that I currently have a ship that moves and the asteroid is drawn at a random size and random x coordinate. I just need to know about how to go about making the asteroid move down while creating other new asteroids that will also move down.
Thank You for all your help! I am new to javascript.
// JavaScript Document
////// Variables //////
var canvas = {width:300, height:500, fps:30};
var score = 0;
var player = {
x:canvas.width/2,
y:canvas.height-100,
defaultSpeed: 5,
speed: 10
};
var asteroids = {
size: Math.floor((Math.random() * 40) + 15),
startY: 100,
startX: Math.floor((Math.random() * canvas.width-200) + 200),
speed: 1
}
var left = false;
var right = false;
////// Arrow keys //////
function onkeydown(e) {
if(e.keyCode === 37) {
left = true;
}
if(e.keyCode === 39) {
right = true;
}
}
function onkeyup(e) {
if (e.keyCode === 37) {
left = false;
}
if(e.keyCode === 39) {
right = false;
}
}
////// other functions //////
//function to clear canvas
function clearCanvas() {
ctx.clearRect(0,0,canvas.width,canvas.height);
}
// draw the score in the upper left corner
function drawscore(score) {
var score = 0;
ctx.fillStyle = "#FFFFFF";
ctx.fillText(score,50,50);
}
// Draw Player ship.
function ship(x,y) {
var x = player.x;
var y = player.y;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x+15,y+50);
ctx.lineTo(x-15,y+50);
ctx.fill();
}
// move player ship.
function moveShip() {
document.onkeydown = onkeydown;
document.onkeyup = onkeyup;
if (left === true && player.x > 50) {
player.x -= player.speed;
}
if (right === true && player.x < canvas.width - 50) {
player.x += player.speed;
}
}
// Draw Asteroid
function drawasteroid() {
this.x = asteroids.startX;
this.y = 100;
this.size = asteroids.size;
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo(this.x,this.y-this.size*0.5);
ctx.lineTo(this.x+this.size*0.9,this.y);
ctx.lineTo(this.x+this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x,this.y+this.size*1.5);
ctx.lineTo(this.x-this.size*0.9,this.y+this.size*1);
ctx.lineTo(this.x-this.size*0.9,this.y);
ctx.fill();
}
// move Asteroid
function moveAsteroid() {
//don't know how I should go about this.
}
// update
setInterval (update, 1000/canvas.fps);
function update() {
// test collisions and key inputs
moveShip();
// redraw the next frame of the animation
clearCanvas();
drawasteroid();
drawscore();
ship();
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Game</title>
<script src="game-functions.js"></script>
<!--
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
-->
</head>
<body>
<canvas id="ctx" width="300" height="500" style="border: thin solid black; background-color: black;"></canvas>
<br>
<script>
////// Canvas setup //////
var ctx = document.getElementById("ctx").getContext("2d");
</script>
</body>
</html>
You want to make the creation of asteroids dynamic...so why not set up a setInterval that gets called at random intervals as below. You don't need a separate declaration for each Asteroids object you create. You can just declare a temporary one in a setInterval function. This will instantiate multiple different objects with the same declaration. Of course you need to store each object somewhere which is precisely what the array is for.
You also have to make sure that asteroids get removed from the array whenever the moveAsteroid function is called if they are off of the canvas. The setInterval function below should be called on window load and exists alongside your main rendering setInterval function.
You are also going to have to change your moveAsteroid function a bit to be able to point to a specific Asteroids object from the array. You can do this by adding the Asteroids object as a parameter of the function or by making the function a property of the Asteroids class and using this. I did the latter in the example below.
var astArray = [];
var manageAsteroidFrequency = 2000;
var Asteroids {
X: //something
Y://something
speed:1
move: function() {
this.X -= speed;
}
}
var mainRenderingFunction = setInterval( function() {
for (var i = astArray.length-1 ; i > -1; i --){
if(astArray[i].Y < 0){
astArray.splice(i, 1)
}else{
astArray[i].move;
}
}
}, 40);
var manageAsteroids = setInterval( function () {
if (astArray.length < 4){
var tmpAst = new Asteroids();
astArray.push(tmpAst);
}
manageAsteroidFrequency = Math.floor(Math.random()*10000);
}, manageAsteroidFrequency);

Javascript on html Canvas element problem

So I'm trying to create a method where the you move an image around a canvas element. This is relevant in that in creating many kinds of games, you'd need a background image to move around properly against the canvas and the player's movement. The problem is that you always draw relative to the canvas's (0,0) point in the top left corner. So what I'm going for in a conceptualization where pressing right (for example) would be conceived as moving the CANVAS right, when really you're moving the image left. It could be argued that this is unnecessary, but honestly thinking about it the other way kind of gives me a headache. I think this way of relating everything to a larger absolute field would be easier to program with a large number of objects.
The problem is, I've messed around with my code in Pycharm but I keep getting canvas not defined and similar errors. Please help me fix this up! So without further ado, here's my code! (and any other ways to clean up my code is appreciated, I'm pretty new to JS!)
//Animates a moving black dot on the canvas.
//Variables for parameters
var gameloopId;
var speed=6;
var canvas;
var background;
var circle;
var ctx;
//Wait for document to be ready then start
$(document).ready(function(){
console.log('document is ready');
init();
});
//Holds the relative coordinates.
function Canvas(){
this.x=0;//relative X
this.y=0;//relative Y
//Calulate screen height and width
this.width = parseInt($("#canvas").attr("width"));
this.height = parseInt($("#canvas").attr("height"));
}
canvas=new Canvas();
//Define an object
function Object(){
this.absX=0;
this.absY=0;
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
}
//Circle Object
function Circle(radius){
this.radius=radius;
}
Circle.prototype= new Object(); //Circle is an Object
function drawCircle(){
// Create the circle
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
Background= Image();
Background.prototype=new Object(); //Background is an Object
background= new Background()
function drawBackground(){
//draw the background
ctx.drawImage(background,background.x,background.y);
}
function init(){
console.log('function init()');
initSettings();
//Insert event handler for keyboard movement of circle (space clearInterval)
$(document).keydown(function(e){
if(e.keyCode=='37'){ //Left key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='38'){ //Up key
circle.absY-=speed;
canvas.y-=speed;}
if(e.keyCode=='39'){ //Right key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='40'){ //Down key
circle.absX+=speed;
canvas.y+=speed;}
if(e.keyCode=='32'){ //Space Bar
console.log('spacebar');
clearInterval(gameloopId);
initSettings();
gameloopId = setInterval(gameLoop,10);
}
});
$(document).keyup(function(e){
if(e.keyCode=='37'){
console.log('left');}//Left key
if(e.keyCode=='38'){
console.log('up');}//Up key
if(e.keyCode=='39'){
console.log('right');}//Right key
if(e.keyCode=='40'){
console.log('down');}//Down key
});
//Initialize loop of "game"
gameloopId = setInterval(gameLoop,10);
}
function initSettings(){
console.log('initSettings');
//Set up canvas
ctx = document.getElementById('canvas').getContext('2d');
//center circle on the horizontal axis
console.log('setting circle coords');
circle = new Circle(15);
circle.x = parseInt(canvas.width/2);
circle.y = canvas.height - 40;
//Put background at (0,0)
background.x=0;
background.y=0;
background.src="http://127.0.0.1:8000/static/back.jpg";
console.log("background width:"+background.width);
console.log("background height:"+background.height);
}
function gameLoop(){
//console.log('function gameLoop()');
//Has it reached far left side?
if(circle.x<circle.radius)
{
circle.x=circle.radius
}
//Has it reached far right side?
if(circle.x>canvas.width - circle.radius)
{
circle.x=canvas.width - circle.radius
}
//Has it reached top?
if(circle.y<circle.radius)
{
circle.y=circle.radius
}
//has it reached bottom?
if(circle.y>canvas.height - circle.radius)
{
circle.y=canvas.height - circle.radius
}
//has background reached left?
if(background.x < canvas.width-background.width)
{
background.x= canvas.width-background.width;
}
//has background reached right?
if(background.x>0)
{
background.x=0;
}
//has background reached top?
if(background.y < canvas.height-background.height)
{
background.y = canvas.height-background.height;
}
//has background reached bottom?
if(background.y>0)
{
background.y=0;
}
//Clear the screen (i.e. a draw a clear rectangle the size of the screen)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//draw background
drawBackground();
// draw the circle
drawCircle();
ctx.restore();
}
EDIT:(UPDATED CODE!)
//Animates a moving black dot on the canvas.
//Variables for parameters
var gameloopId;
var speed=6;
var canvas;
var background;
var circle;
var ctx;
//Wait for document to be ready then start
$(document).ready(function(){
console.log('document is ready');
init();
});
//Holds the relative coordinates.
function Canvas(){
this.x=0;//relative X
this.y=0;//relative Y
//Calulate screen height and width
this.width = parseInt($("#canvas").attr("width"));
this.height = parseInt($("#canvas").attr("height"));
}
//Define an object
function MyObject(){
this.absX=0;
this.absY=0;
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
}
//Circle MyObject
function Circle(radius){
this.radius=radius;
}
Circle.prototype= new MyObject(); //Circle is an MyObject
function drawCircle(){
// Create the circle
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
function Background(){
this.img= Image();
}
Background.prototype=new MyObject(); //Background is an MyObject
function drawBackground(){
//draw the background
ctx.drawImage(background,background.x,background.y);
}
function init(){
console.log('function init()');
initSettings();
//Insert event handler for keyboard movement of circle (space clearInterval)
$(document).keydown(function(e){
if(e.keyCode=='37'){ //Left key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='38'){ //Up key
circle.absY-=speed;
canvas.y-=speed;}
if(e.keyCode=='39'){ //Right key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='40'){ //Down key
circle.absX+=speed;
canvas.y+=speed;}
if(e.keyCode=='32'){ //Space Bar
console.log('spacebar');
clearInterval(gameloopId);
initSettings();
gameloopId = setInterval(gameLoop,10);
}
});
$(document).keyup(function(e){
if(e.keyCode=='37'){
console.log('left');}//Left key
if(e.keyCode=='38'){
console.log('up');}//Up key
if(e.keyCode=='39'){
console.log('right');}//Right key
if(e.keyCode=='40'){
console.log('down');}//Down key
});
//Initialize loop of "game"
gameloopId = setInterval(gameLoop,10);
}
function initSettings(){
console.log('initSettings');
//Set up canvas
canvas=new Canvas();
ctx = document.getElementById('canvas').getContext('2d');
//center circle on the horizontal axis
console.log('setting circle coords');
circle = new Circle(15);
circle.x = parseInt(canvas.width/2);
circle.y = canvas.height - 40;
//Put background at (0,0)
background= new Background();
background.x=0;
background.y=0;
background.img.src="http://127.0.0.1:8000/static/back.jpg";
console.log("background width:"+background.width);
console.log("background height:"+background.height);
}
function gameLoop(){
//console.log('function gameLoop()');
//Has it reached far left side?
if(circle.x<circle.radius)
{
circle.x=circle.radius
}
//Has it reached far right side?
if(circle.x>canvas.width - circle.radius)
{
circle.x=canvas.width - circle.radius
}
//Has it reached top?
if(circle.y<circle.radius)
{
circle.y=circle.radius
}
//has it reached bottom?
if(circle.y>canvas.height - circle.radius)
{
circle.y=canvas.height - circle.radius
}
//has background reached left?
if(background.x < canvas.width-background.width)
{
background.x= canvas.width-background.width;
}
//has background reached right?
if(background.x>0)
{
background.x=0;
}
//has background reached top?
if(background.y < canvas.height-background.height)
{
background.y = canvas.height-background.height;
}
//has background reached bottom?
if(background.y>0)
{
background.y=0;
}
//Clear the screen (i.e. a draw a clear rectangle the size of the screen)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//draw background
drawBackground();
// draw the circle
drawCircle();
ctx.restore();
}
enter code here
I don't think you can write your own Object You definitely can't use Object, it's a reserved keyword. Object is the built in javascript object that all objects inherit from. You have basically overwritten it. That could be your problem.
Try calling it myObject to check if this is the problem.
//Define an myObject
function myObject(){
this.absX=0;
this.absY=0;
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
}
Circle.prototype= new myObject(); //Circle is a myObject
Background= Image();
Background.prototype=new Object(); //Background is an Object
background= new Background()
seems suspicious.
edit : Background is an Element. You add a prototype even though it is not a function.
Then you call Background as a constructor but it is not.
So background is likely to be undefined. I am surprised background.x gives you 0.
By the way, you should parseInt(arg, 10) to get your result in decimal and not octal.
I figured it out! I had a lot of stupid stuff in my ode and lots of bugs - for example background.img is an Image, but all over the place I was trying to get background.width instead of background.img.width. I also refactored several functions to make things prettier (to em at least). Thanks to the above for your help! Here's my "final" code, at least as of right now:
//Animates a moving black dot on the canvas.
//Variables for parameters
var gameloopId;
var speed=6;
//var canvas;
var background;
var circle;
var ctx;
//Wait for document to be ready then start
$(document).ready(function(){
console.log('document is ready');
init();
});
//Holds the relative coordinates.
var canvas = new function Canvas(){
this.x=0;//relative X
this.y=0;//relative Y
//Calulate screen height and width
this.width = parseInt($("#canvas").attr("width"));
this.height = parseInt($("#canvas").attr("height"));
};
//Define an object
function MyObject(){
this.absX=0;
this.absY=0;
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
this.updateplace = function (){
this.x=this.absX-canvas.x;
this.y=this.absY-canvas.y;
};
}
//Circle MyObject
function Circle(radius){
this.radius=radius;
this.draw=function(){
// Create the circle
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#000000";
ctx.beginPath();
ctx.arc(circle.x,circle.y,circle.radius,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
}
Circle.prototype= new MyObject(); //Circle is an MyObject
function Background(){
this.img= Image();
this.draw=function(){
ctx.drawImage(background.img,background.x,background.y);
}
}
Background.prototype=new MyObject(); //Background is an MyObject
function init(){
console.log('function init()');
initSettings();
//Insert event handler for keyboard movement of circle (space clearInterval)
$(document).keydown(function(e){
if(e.keyCode=='37'){ //Left key
circle.absX-=speed;
canvas.x-=speed;}
if(e.keyCode=='38'){ //Up key
circle.absY-=speed;
canvas.y-=speed;}
if(e.keyCode=='39'){ //Right key
circle.absX+=speed;
canvas.x+=speed;}
if(e.keyCode=='40'){ //Down key
circle.absY+=speed;
canvas.y+=speed;}
if(e.keyCode=='32'){ //Space Bar
console.log('spacebar');
clearInterval(gameloopId);
initSettings();
gameloopId = setInterval(gameLoop,10);
}
});
$(document).keyup(function(e){
if(e.keyCode=='37'){
console.log('left');}//Left key
if(e.keyCode=='38'){
console.log('up');}//Up key
if(e.keyCode=='39'){
console.log('right');}//Right key
if(e.keyCode=='40'){
console.log('down');}//Down key
});
//Initialize loop of "game"
gameloopId = setInterval(gameLoop,10);
}
function initSettings(){
console.log('initSettings');
//Set up canvas
ctx = document.getElementById('canvas').getContext('2d');
canvas.width = parseInt($("#canvas").attr("width"));
canvas.height = parseInt($("#canvas").attr("height"));
//center circle on the horizontal axis
console.log('setting circle coords');
circle = new Circle(15);
circle.absX = parseInt(canvas.width/2);
circle.absY = canvas.height - 40;
//Put background at (0,0)
background= new Background();
background.x=0;
background.y=0;
background.img.src="http://127.0.0.1:8000/static/back.jpg";
console.log("background width:"+background.img.width);
console.log("background height:"+background.img.height);
console.log("Right Bound:"+(background.img.width- canvas.width))
}
function gameLoop(){
//console.log('function gameLoop()');
//Has it reached far left side?
if(circle.absX<circle.radius)
{
circle.absX=circle.radius
}
//Has it reached far right side?
if(circle.absX>background.img.width - circle.radius)
{
circle.absX=background.img.width - circle.radius
}
//Has it reached top?
if(circle.absY<circle.radius)
{
circle.absY=circle.radius
}
//has it reached bottom?
if(circle.absY>background.img.height - circle.radius)
{
circle.absY=background.img.height - circle.radius
}
//has canvas reached right bound?
if(canvas.x > background.img.width- canvas.width)
{
canvas.x= background.img.width- canvas.width;
}
//has canvas reached left bound?
if(canvas.x<0)
{
canvas.x=0;
}
//has background reached bottom bound?
if(canvas.y > background.img.height - canvas.height)
{
canvas.y = background.img.height - canvas.height;
}
//has background reached top bound?
if(canvas.y<0)
{
canvas.y=0;
}
//Clear the screen (i.e. a draw a clear rectangle the size of the screen)
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
//draw background
background.updateplace();
background.draw();
// draw the circle
circle.updateplace();
circle.draw();
ctx.restore();
}

Categories