Draw rectangles dynamically in SVG

后端 未结 1 1419
旧巷少年郎
旧巷少年郎 2020-12-30 02:22

I would like to know how to draw 100 rectangles with SVG.

I made one rectangle with this code:




        
1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-30 03:24

    You can fill the screen with the following loop:

    var svgns = "http://www.w3.org/2000/svg";
    for (var x = 0; x < 5000; x += 50) {
        for (var y = 0; y < 3000; y += 50) {
            var rect = document.createElementNS(svgns, 'rect');
            rect.setAttributeNS(null, 'x', x);
            rect.setAttributeNS(null, 'y', y);
            rect.setAttributeNS(null, 'height', '50');
            rect.setAttributeNS(null, 'width', '50');
            rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
            document.getElementById('svgOne').appendChild(rect);
        }
    }
    

    If you just want 100 randomly placed squares, you could do:

    for (var i = 0; i < 100; i++) {
        var x = Math.random() * 5000,
            y = Math.random() * 3000;
    
        var rect = document.createElementNS(svgns, 'rect');
        rect.setAttributeNS(null, 'x', x);
        rect.setAttributeNS(null, 'y', y);
        rect.setAttributeNS(null, 'height', '50');
        rect.setAttributeNS(null, 'width', '50');
        rect.setAttributeNS(null, 'fill', '#'+Math.round(0xffffff * Math.random()).toString(16));
        document.getElementById('svgOne').appendChild(rect);
    }
    

    jsfiddle for the second one

    0 讨论(0)
提交回复
热议问题