2015-11-21 2 views
0

Я пытаюсь создать фон в холсте, и некоторые небольшие круги просто текут по всему фону, в конце концов я изменю фигуры и добавлю больше деталей, но у меня просто возникают проблемы с настройкой.Настройка фоновой анимации холста

Я знаю, что мой код janky, но есть ли какие-либо предложения в отношении структуры кода?

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; 

    } 
+0

Не могли бы вы дать нам изображение того, что произойдет, пожалуйста? :) – Arpp

+0

На самом деле я не получаю ничего всплывающего, и ошибок нет :( Я чувствую, что у меня есть правильные части, но структура отключена, и я помещаю вещи в неправильные места – Jclee

+0

Вы вызывали функции? не знаю, что смогу помочь вам с частичным кодом. – Arpp

ответ

0

Я пытался кодировать рабочий пример. Здесь звезды постоянно появляются.

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); 

Вот скрипка: 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>