所以我在网站上有一个横幅,但我想让它每次加载页面时都会出现不同的图像。更准确地说,我想要(比如 50)个随机大小(比如从 5 像素到 20 像素大小)的正方形(比如 50 个),位于 750x63 像素帧的随机位置,背景为白色。
最好的方法是什么?我知道一点 JavaScript 和 HTML(并且非常愿意学习更多),但我真的不知道从哪里开始。这是我的个人网页,我希望对其进行一些修饰。现在我拥有的最漂亮的代码是一些用于简单 Lightbox 界面的 JavaScript。
哇,这比我预期的要容易和有趣。这是<body>
我的 HTML 代码部分中的代码,针对 750x80px 框架进行了优化。我从另一个问题中得到的随机整数生成器。
<canvas id="canvas" width="750" height="80"></canvas>
<script type="text/javascript">
//Random integer generator
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
//Loop to make 80 squares
for (var i=0;i<80;i++) {
//The x-position of the square, with 5px padding in frame
var sx = getRandomInt(5,705);
//The y-position of the square, with 5px padding in frame
var sy = getRandomInt(5,35);
//The height of the square, smallest 8x8px, largest 40x40px
var sh = getRandomInt(8,40);
//First, create a black square
ctx.fillStyle = "rgb(0,0,0)";
ctx.fillRect (sx, sy, sh, sh);
//Second, create a white square that's 4px shorter and thinner,
//leaving a boundary of 2px
ctx.fillStyle = "rgb(255,255,255)";
ctx.fillRect (sx+2, sy+2, sh-4, sh-4);
}
}
draw();
</script>
我使用的方法来自Mozilla 开发者页面。结果是这样的:
万岁!