0
我無法動態地將框添加到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);
}
沒有被顯示在頁面上,通過調試似乎它具有的屬性問題。我不確定該從哪裏出發。
哪些錯誤在控制檯拋出? –
@BramVanroy嗯,它是拋出錯誤,它得到的箱子[我] .something(。寬,.x,.y等)。但現在它甚至沒有顯示任何錯誤,也沒有顯示任何框。 – user2619395
在'boxes [i] .y'之後,你在最後一行的第六行有兩個逗號。這些意味着如此嗎? –