【发布时间】:2015-11-21 08:19:19
【问题描述】:
我正在尝试在画布中设置背景,并且在整个背景中流动一些小圆圈,最终我将更改形状并添加更多细节,但我只是在设置时遇到了问题。
我知道我的代码很乱,但是对代码结构有什么建议吗?
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;
}
【问题讨论】:
-
您能给我们一张图片,看看会发生什么吗? :)
-
我实际上没有弹出任何东西,也没有错误:(我觉得我有正确的部分,但结构是关闭的,我把东西放在错误的地方
-
你调用函数了吗?我不确定我能否为您提供部分代码。
-
除此之外,我唯一拥有的是一些 html 骨架和一个高度和宽度为 1000 的画布 ID。这就是其他一切。我只需要一个正确方向的光,我正在画布上制作一个背景,它有一个静态背景,带有在屏幕上移动的小圆圈。这些都是我需要的功能吗?
-
尝试调用 init()。无论如何,我看不到您是如何构建游戏循环的。我会尝试进一步研究。看看我下面的代码。每 16 毫秒,浏览器将执行游戏循环中的代码,位于底端(我放置 draw() 函数的位置)。
标签: javascript animation canvas background move