2013-04-11 62 views
0

所以我在網站上有一個橫幅,但是我想這樣做是爲了每次頁面加載時出現不同的圖像。更確切地說,我想要一個750x63像素幀的隨機位置(白色填充),具有白色背景的隨機大小(比如從5像素到20像素)的50個方塊(比如有黑色邊框,白色填充)。在每個頁面生成一個包含特定內容的隨機圖像刷新/刷新

這樣做的最好方法是什麼?我知道一些JavaScript和HTML(我非常願意學習更多),但我真的不知道從哪裏開始。這是我的個人網頁,我想稍微修改一下。現在,我擁有的最簡單的代碼是一些用於簡單燈箱界面的JavaScript。

回答

0

哇,這比我預期的更容易,更有趣。以下代碼位於我的HTML代碼的<body>部分,針對750x80像素的幀進行了優化。隨機整數發生器我從this other question得到。

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

我使用的方法是從a Mozilla Developers page。其結果是這樣的:

the result

萬歲!