有没有一种好方法可以添加新框并使用 javascript 重新绘制画布

Is there a nice way to add new box and redraw the canvas using javascript?

本文关键字:javascript 新绘制 绘制 添加 一种 方法 有没有 新框      更新时间:2023-09-26

底层代码在画布中创建随机块。这就是我迄今为止取得的成就。但是我很难做进一步的任务。我想在画布外制作一个按钮(绝对很容易),单击该按钮会在画布中添加一个新框。旧盒子的位置可能会也可能不会改变(它提供适当的空间)。如果没有足够的空间容纳新框,请增加内部容器的大小,这将增加画布的大小,并用新画布比例重新绘制旧框。如果内部容器尺寸增加外部容器,则滚动条将出现在外部容器中。这是我当前的代码:

目录:

<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() 函数来绘制您想要的任何内容。