svg pixel art generator

generate svg avatar

by slawe

HTML

<svg id="SVG_scene" xmlns="http://www.w3.org/2000/svg"></svg>

<canvas id="CANVAS_scene" width="200" height="200"></canvas>

CSS

canvas {margin-left: 50px;}

JavaScript

function getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function getRandomArray(length) {
    let arr = [],
        countZero = 0,
        countOne = 0;
    for (let index = 0; index < length; index++) {
        arr[index] = {
            values: [],
            cf: 0.5
        };
    }
    // actions with arrays
    arr[0].cf = 0.95;
    arr[1].cf = 0.9;
    arr[2].cf = 0.8;
    arr[ arr.length - 1 ].cf = 0.9;

    for ( let index = 0; index < length; index++ ) {
        let x = 0;
        for (; x < length / 2; x++) {
            let rnd = Math.random();
            if ( rnd > arr[index].cf ){
                countZero++;
                arr[index].values[x] = 0;
            } else {
                countOne++;
                arr[index].values[x] = 1;
            }
        }
        for (; x < length; x++) {
            arr[index].values[x] = arr[index].values[length - 1 - x];
        }
    }

    let division = countOne / countZero;
    
    if ( division === 1 )
    	console.warn('Attitude 1!');

    return arr;
}

function drawSVG(svg, arr, length, color='#000') {
  while (svg.hasChildNodes()) {
  	svg.removeChild(svg.firstChild);
	}
  
  let setAttrs = (e,a)=>Object.entries(a).forEach(([k,v])=>e.setAttribute(k,v));
  
  let svgns = "http://www.w3.org/2000/svg";

  // change any value
  let width = 200/length,
  		height = width,
      counter = 0,
  		// figure the new svg width/height
  		svgWidth = Math.floor(document.documentElement.clientHeight / 100) * 100,
  		svgHeight = svgWidth;

  setAttrs(svg, {
  	width: svgWidth,
    height: svgHeight,
    viewBox: "0 0 " + svgWidth + " " + svgHeight
  });
  
  for (let j = 0; j < length; j++) {
    for (let i = 0; i < length; i++) {
      counter++;
      let newRect = document.createElementNS(svgns, "rect");
      setAttrs(newRect, {
        x: i * width,
       ...