0

I'm trying to set up a background in canvas and have some small circles just flow throughout the background, eventually I'll change the shapes and add more details in, but I'm just having trouble with the set up.

I know my code is janky, but are there any suggestions to the structure of the code?

    var dx = 1;
    var dy = 2;
    var circle=new Circle(400,30,10);
    var timer;


    function Circle(x,y,r){
    this.x=x;
    this.y=y;
    this.r=r;
}

    function init() {

    // Get the canvas element.
    canvas = document.getElementById("canvas");


    if (canvas.getContext) {
        ctx = canvas.getContext("2d");
        ctx.fillStyle = "black";
    }
     timer=setInterval(draw, 10);
     return timer;
}


  function gradient (){
    var my_gradient=ctx.createLinearGradient(0,0,1000,0);
        my_gradient.addColorStop(0,"black");
        my_gradient.addColorStop(1,"white");
        ctx.fillStyle=my_gradient;
        ctx.fillRect(0,0,1000,1000); 
        ctx.rect(0, 0, 1000, 1000);
        stars();

   }


   function stars(){
    for (i = 0; i <= 50; i++) {
      // Get random positions for stars
      var x = Math.floor(Math.random() * 1000)
      var y = Math.floor(Math.random() * 1000)
       ctx.fillStyle = "yellow";

    //if (x < 30 || y < 30) ctx.fillStyle = "black";

     ctx.beginPath();
      ctx.arc(x, y, 3, 0, Math.PI * 2, true);
      ctx.closePath();
      ctx.fill();
    } 
}
    function move(){
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = gradient.my_gradient;
    ctx.fillRect(0,0,canvas.width,canvas.height);
    ctx.fillStyle = "#003300";
    drawBall(circle);
    if (circle.x +dx > canvas.width || circle.x +dx < 0)
    dx=-dx;
    if(circle.y+dy>bar.y && circle.x>bar.x &&         circle.x<bar.x+barImg.width)
    dy=-dy;
    if (circle.y +dy > canvas.height || circle.y +dy < 0)
    dy=-dy;
    circle.x += dx;
    circle.y += dy;

    }
Jclee
  • 39
  • 9
  • Could you give us an image of what happens please ? :) – Arpp Nov 21 '15 at 08:34
  • I actually dont get anything to pop up, and there are no errors :( I feel like I have the right parts but the structure is off and I'm putting things in wrong places – Jclee Nov 21 '15 at 09:12
  • Have you called functions ? I am not sure I can help you with a partial code. – Arpp Nov 21 '15 at 09:14
  • The only thing I have besides this is some html skeleton and a canvas id with height and width of 1000. This is everything else. I just need a light in the right direction, I'm making a background in canvas that has a static background with little circles that move across the screen. Are these all the functions I need? – Jclee Nov 21 '15 at 09:25
  • Try to call init(). Anyway, I do not see how you built your game loop. I will try to look further. Look at my code below. Each 16ms, the browser will execute the code in the gameloop, at the bottom end (where I put my draw() function). – Arpp Nov 21 '15 at 09:30
  • The draw function I understand, the gameLoop, not so much. Lemme word my question like this. I have my initial function, background function, drawShape function and animation function. Is that the correct functions to have for this canvas animation background to work? – Jclee Nov 21 '15 at 09:36
  • Hm. Functions themselves are correct. But you have to set a game loop and call functions each time : see http://stackoverflow.com/questions/1955687/best-way-for-simple-game-loop-in-javascript. Then, I see few mistakes in your code. For exemple, you call drawBall(), but you do not define this function. – Arpp Nov 21 '15 at 09:46
  • Sorry, I assumed your project was a game, but what I call a game loop is just a loop, which is used to update the state of your app (calculate some stuff, render it to the screen, get user inputs if needed, etc.). Basically, you can use a setInterval function to create this loop, but some more advanced techniques improve results (search on the web for "game loop javascript"). Notice that an app loop is not an infinite true loop like while(true){}... Once the loop is there, update your app continuously by calling your functions (i.e. background function, drawShap, etc.). – Arpp Nov 21 '15 at 09:55
  • Yeah I'm still in the middle of editing it, so can this loop function be in the animation function? – Jclee Nov 21 '15 at 10:01
  • Wait... By "animation function", do you mean a function animating your app objects by calculating new positions, or a function which call other function at a regular interval (that is to say what I call a game loop or an app loop) ? If my first proposal is the one correct, this animation function is inside the app loop. – Arpp Nov 21 '15 at 10:06
  • I'm trying to go about having random objects constantly being calculated to give the appearance of animation. So I put my animation function inside of an if else loop for my objects? – Jclee Nov 21 '15 at 10:15
  • I edited my post below, with a working exemple and few comments. – Arpp Nov 21 '15 at 11:16

1 Answers1

0

I tried to code a working exemple. Here stars are popping up continuously.

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Exemple</title>
</head>
<body>

    <canvas id="viewport"></canvas>
    <script src='test.js'></script>

</body>
</html>

JS

var doc     = document;
var canvas  = doc.getElementById('viewport');
var ctx     = canvas.getContext('2d');

var settings = {
    area : { 
        height  : 100, 
        width   : 100
    }
};
canvas.width  = settings.area.width;
canvas.height = settings.area.height;

function draw() {
    for (var i = 10; i--;) {
        var x = Math.floor(Math.random() * 1000)
        var y = Math.floor(Math.random() * 1000)

        ctx.beginPath();
        ctx.arc(x, y, 3, 0, Math.PI * 2, true);
        ctx.fillStyle = "yellow";
        ctx.closePath();
        ctx.fill();
    }
}

function gameLoop (render, element) {
    var running, lastFrame = +new Date;
    function loop( now ) {
        // stop the loop if render returned false
        if ( running !== false ) {
            requestAnimationFrame( loop, element );
            running = render( now - lastFrame );
            lastFrame = now;
        }
    }
    loop( lastFrame );
}

gameLoop (function (deltaT) {

    draw();

}, canvas );

Here is the fiddle : https://jsfiddle.net/q4q0uLht/

----- EDIT -----

/*
Basic config
*/
var doc = document, 
    canvas = doc.getElementById('viewport'), 
    ctx = canvas.getContext('2d');

var settings = {
    canvas: {
        height: 200,
        width: 300
    }
}
canvas.height = settings.canvas.height;
canvas.width = settings.canvas.width;
canvas.style.border = '1px #000 solid';

/*
easy gets a random number, inside a range of [0, x);
*/
function getRandomNumber(x) {
    return parseInt(Math.random() * x, 10);
}

/*
Checks if the obj passed in argument is still in the canvas limits
*/
function incorrectPosition(obj) {
    return obj.x < 0 || obj.y < 0 || obj.x > settings.canvas.width || obj.y > settings.canvas.height;
}

/*
stars array and Star object.
*/
var stars = [];
function Star(r) {
    this.x = getRandomNumber(canvas.width);
    this.y = getRandomNumber(canvas.height);
    this.r = r || 10;
    this.move = function(dx, dy) {
        this.x += dx;
        this.y += dy;
    };
}


/*
This function adds new stars, 
calculates new coordinates of each star,
and removes them from the stars array 
when they are out of the canvas limits.
*/
function update() {
    var len = stars.length;
    if (len < 10) {
        stars.push(new Star());
    }
    for (var i = len; i--;) {
        var star = stars[i];
        star.move(1, 2);
        if (incorrectPosition(star)) {
            stars.splice(i, 1);
        }        
    }
}

/*
This function clears the canvas each turn and
draws each star which is stored inside the stores array.
*/
function draw() {
    ctx.clearRect(0, 0, settings.canvas.width, settings.canvas.height);
    var len = stars.length;
    for (var i = len; i--;) {
        var star = stars[i];
        ctx.beginPath();
        ctx.arc(star.x, star.y, 3, 0, Math.PI * 2, true);
        ctx.fillStyle = "yellow";
        ctx.closePath();
        ctx.fill();
    }
}


// Here is the loop inside which are called functions
setInterval(loop, 33);
function loop() {
    
    update(); // update first
    draw(); // then draw
    
}
<!DOCTYPE html>
<html>
<head>
    <title>Exemple</title>
</head>
<body>
        
    <canvas id="viewport"></canvas>
    <script src='test.js'></script>

</body>
</html>
Arpp
  • 301
  • 1
  • 11