【发布时间】:2014-02-25 18:26:06
【问题描述】:
我想写一个简单的从右到左滚动的starfield。我随机打印出星星。现在,我如何瞄准每颗星星并随机给它一个速度(比如 1-10)并开始移动它?我还需要在每颗星星到达左边缘后将其放回右边缘。
以下是我目前编写的代码:
<!DOCTYPE html>
<html>
<head>
<script>
function stars()
{
canvas = document.getElementById("can");
if(canvas.getContext)
{
ctx = canvas.getContext("2d");
ctx.fillStyle = "black";
ctx.rect (0, 0, 400, 400);
ctx.fill();
starfield();
}
}
//print random stars
function starfield()
{
for (i=0; i<10; i++)
{
var x = Math.floor(Math.random()*399);
var y = Math.floor(Math.random()*399);
var tempx = x;
ctx.fillStyle = "white";
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
}
}
</script>
</head>
<body onload="stars()">
<h1>Stars</h1>
<canvas id="can" width="400" height="400"style="border:2px solid #000100" ></canvas>
</body >
</html>
【问题讨论】:
-
你可以使用 jQuery 解决方案吗?
-
对不起,我不使用 jquery。目前还在努力学习 js :)
-
您只需为我使用 jQuery 解决方案发布的答案导入一个外部文件
-
检查我的答案。如果它非常适合你,那么我可以发布整个代码
标签: javascript html