簡體   English   中英

在頁面上動態創建框

[英]Create Boxes Dynamically on a Page

我在將框動態添加到HTML畫布時遇到麻煩。 在隨機位置應有隨機數量的隨機顏色的盒子。 我正在使用盒子的目的是要能夠移動它們。 本質上我真的迷路了。

這是html代碼:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Ramdom Boxes</title>
        <script src="A2Q1.js"></script>
    </head>

    <body>      
    </body>
</html>

這是Javascript代碼:

window.onload = init;

function init() {
    //when page is loaded create a bunch of boxes randomly throughout the page
    //get the body element of the document
    var body = document.getElementsByTagName("body")[0];

    //create the canvas tag
    var canvas = document.createElement("canvas");
    canvas.height = 666;
    canvas.width = 1346;
    var context = canvas.getContext("2d");

    //create the random boxes and append onto the canvas
    var randNum = Math.floor(Math.random() * 1000 + 1);

    var boxes = [];
    for(var i=0;i<randNum;i++){
        boxes[i].height = 50;
        boxes[i].width = 50;
        boxes[i].x = Math.floor(Math.random() * (1346 - boxes[i].width));
        boxes[i].y = Math.floor(Math.random() * (666 - boxes[i].height));

        boxes[i].colour = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    }

    for(var i=0;i<boxes.length;i++){
        context.fillStyle = colour;
        context.fillRect(boxes[i].x, boxes[i].y, , boxes[i].height); 
    }

    //append the canvas onto the body 
    body.appendChild(canvas);
}

該頁面上沒有任何顯示,通過調試,似乎屬性有問題。 我不確定從這里去哪里。

您可以使用砌體jquery插件對框進行排序。

context.fillStyle = colour;

你的意思是

context.fillStyle = boxes[i].colour;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM