[英]Is there a nice way to add new box and redraw the canvas using javascript?
基礎代碼在畫布中創建隨機塊。 這是我到目前為止所取得的成就。 但是我在做進一步的工作時遇到困難。 我想在畫布上創建一個按鈕(肯定很簡單),單擊后在畫布中添加了一個新框。 舊盒子的位置可能會改變,也可能不會改變(直至提供適當的空間)。 如果沒有足夠的空間容納新盒子,則增加內部容器的大小,這將增加畫布的大小,並用新的畫布比例用新的畫布比例重新繪制舊的盒子。 並且如果內部容器的尺寸增加了外部容器的大小,則滾動條將進入外部容器。 這是我當前的代碼:
HTML:
<div class="outer-container">
<div class="inner-container">
<canvas id="canvas" style="height:100%;width:100%"></canvas>
</div>
</div>
Javascript:
function getRandomColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
color += (Math.random() * 16 | 0).toString(16);
}
return color;
}
function Point(x, y) {
this.x = x;
this.y = y;
}
function Rectangle(p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
Rectangle.prototype.isInside = function (r) {
function check(a, b) {
return (
a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y ||
a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y ||
a.p1.x <= b.p2.x && b.p2.x <= a.p2.x && a.p1.y <= b.p1.y && b.p1.y <= a.p2.y ||
a.p1.x <= b.p1.x && b.p1.x <= a.p2.x && a.p1.y <= b.p2.y && b.p2.y <= a.p2.y
);
}
return check(this, r) || check(r, this);
}
function generateRectangles() {
function p() { return Math.random() * 300 | 0; }
function s() { return 50 + Math.random() * 150 | 0; }
var rectangles = [],
r, size, x, y, isInside, i, counter = 0;
for (i = 0; i < 20; i++) {
counter = 0;
do {
counter++;
x = p();
y = p();
size = s();
r = new Rectangle(new Point(x, y), new Point(x + size, y + size));
isInside = rectangles.some(function (a) {
return a.isInside(r);
});
} while (isInside && counter < 1000);
counter < 1000 && rectangles.push(r);
}
return rectangles;
}
function drawRectangles(rectangles) {
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
rectangles.forEach(function (a) {
ctx.lineWidth = 1;
ctx.strokeRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1);
ctx.fillStyle = getRandomColor();
ctx.fillRect(a.p1.x + 0.5, a.p1.y + 0.5, a.p2.x - a.p1.x - 1, a.p2.y - a.p1.y - 1);
});
}
var rectangles = generateRectangles();
drawRectangles(rectangles);
我只是不知道該如何重畫它。 任何幫助將不勝感激。
創建按鈕,帶有onclick =“ draw();” 屬性,以及一個javascript draw()函數繪制所需的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.