У меня возникли проблемы с динамическим добавлением ящиков в 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);
}
На странице ничего не появляется, отлаживая, кажется, что у него проблемы со свойствами. Я не уверен, куда идти отсюда.
context.fillStyle = colour;
Ты имел ввиду
context.fillStyle = boxes[i].colour;
Вы можете использовать плагин jquery masonry для сортировки ящиков.