Mondrian Generator

Developer
Size
21,771 Kb
Views
12,144

How do I make an mondrian generator?

What is a mondrian generator? How do you make a mondrian generator? This script and codes were developed by Devin on 23 November 2022, Wednesday.

Mondrian Generator Previews

Mondrian Generator - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>Mondrian Generator</title> <link href="https://fonts.googleapis.com/css?family=Montez" rel="stylesheet">
<script src="https://use.fontawesome.com/d9eaf45f03.js"></script>
<script src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel="stylesheet" href="css/style.css">
</head>
<body> <div class="card"> <h1 class="header">Mondrian Generator</h1> <div class="main"> <canvas id ="canvas" class="canvas"></canvas> <div class="icons"> <i id="heartButton" class="icon fa fa-heart-o" aria-hidden="true"></i> <i class="icon fa fa-floppy-o save" aria-hidden="true"></i> </div> </div> <div class="buttons"> <button id="favsButton" class="button favsButton"><i class="fa fa-heart" aria-hidden="true"></i></button> <button id="generateButton" class="button generate">Generate</button> <button id="settingsButton" class="button settingsButton"><i class="fa fa-cog" aria-hidden="true"></i></button> </div> <div class="settingsMenu"> <h2 class="header">Settings</h2> <div class="setting"> <label for="pixelSizeInput" title="Size of each 'pixel'">Pixel Size: </label><input id="pixelSizeInput" type="number" min="1" max="10" value="5"> </div> <div class="setting"> <label for="lineCount" title="number of lines drawn on canvas (that will be attempted)"># of Lines: </label><input type="number" min="3" max="50" id="lineCount" value="30"> </div> <div class="setting"> <label for="randomizeSelect" title="Colors will be more random">Randomize: </label> <select id="randomizeSelect" value="true"> <option value="true">True</option> <option value="false">false</option> </select> </div> <div class="setting colorsSetting"> <label title="Colors used in mondrian.">Colors</label> <input type="color" value="#008000" class="colorInput"/> <input type="color" value="#BF0000" class="colorInput"/> <input type="color" value="#E4F7F7" class="colorInput"/> <input type="color" value="#0500EF" class="colorInput"/> <input type="color" value="#FFF700" class="colorInput"/> </div> <div class="settingsButtons"> <button class="button" id="settingsUpdateButton" title="Update settings">Update</button> <button class="button" id="settingsResetButton" title="Reset to defaults">Reset</button> </div> </div> <div class="favsMenu"> <h2 class="header">favorites</h2> <div class="favsMessage"></div> <div class="favorites"></div> </div>
</div> <script src="js/index.js"></script>
</body>
</html>

Mondrian Generator - Script Codes CSS Codes

body { align-items: center; background: #096d94; display: flex; flex-flow: column wrap; height: 100vh; justify-content: center;
}
.icon { align-items: center; cursor: pointer; display: flex; font-size: 20px; justify-content: center; text-shadow: 0px 0px 10px black;
}
.fa-heart-o, .fa-heart { color: pink;
}
.fa-floppy-o, .fa-times { color: #bbb;
}
.fa-floppy-o:hover, .fa-times:hover { color: #ccc;
}
.header { background-image: url("https://image.ibb.co/gfyBjv/light_Wood.png"); box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2); font-family: 'Montez',cursive; font-size: 23px; margin: 0; padding: 5px; position: absolute; text-shadow: 1px 1px rgba(255, 255, 255, 0.4); top: 10px;
}
.main { height: 220px; position: relative; width: 220px;
}
.icons { background: rgba(0, 0, 0, 0.7); display: flex; height: 50px; justify-content: space-around; left: 10px; opacity: 0; position: absolute; top: calc(50% - 25px); transition: opacity .2s; width: calc(100% - 20px);
}
.icons:hover { opacity: 1; transition: opacity .2s;
}
.canvas:hover + .icons { opacity: 1;
}
.card { align-items: center; background: #eee; background-image: url("https://s-media-cache-ak0.pinimg.com/736x/12/a4/b7/12a4b77138481e553ba45b485d5a3956--italian-marble-art-patterns.jpg"); border: 4px solid #ddd; border-radius: 2px; box-shadow: inset 0 0 2px 2px rgba(0, 0, 0, 0.2), 5px 5px 5px rgba(0, 0, 0, 0.2); display: flex; flex-flow: column wrap; min-height: 300px; overflow: hidden; padding: 10px; padding-top: 55px; position: relative; width: 250px;
}
.settingsMenu, .favsMenu { align-items: center; background: black; background-image: url("https://preview.ibb.co/heraBa/marble.jpg"); border-left: 1px solid rgba(0, 0, 0, 0.4); box-shadow: inset 0 0 2px 2px rgba(0, 0, 0, 0.2); display: flex; flex-flow: column wrap; height: 100%; padding-top: 50px; position: absolute; top: 0; transform: translate3d(100%, 0px, 0px); transition: transform .3s; width: 100%;
}
.favsMenu { overflow: hidden; transform: translate3d(-100%, 0px, 0px);
}
.setting { align-items: center; display: flex; height: 50px; margin: 0 auto; width: 80%;
}
.setting label { flex: 1; min-width: 30%; text-shadow: 2px 2px white;
}
.setting input { width: 40%;
}
.colorInput { border: none; padding: 0; margin-left: 8px; min-height: 25px; max-width: 30px; box-shadow: 4px 4px 5px rgba(0, 0, 0, 0.3);
}
.button { background: white; border: none; border: 1px solid rgba(0, 0, 0, 0.4); border-radius: 2px; box-shadow: inset 3px 3px 2px rgba(255, 255, 255, 0.3), inset -3px -3px 2px rgba(0, 0, 0, 0.2); color: #111; cursor: pointer; font-weight: bold; margin: 10px; margin-bottom: 0px; outline: none; padding: 10px;
}
.button:hover { background: #eee; box-shadow: inset -3px -3px 5px rgba(255, 255, 255, 0.6), inset 3px 3px 2px rgba(0, 0, 0, 0.2);
}
.settingsButton, .favsButton { bottom: 5px; font-size: 13px; height: 10px; margin: 0; position: absolute; right: 5px; text-align: center; width: 10px; z-index: 10;
}
.settingsButton .fa-cog, .settingsButton .fa-heart, .settingsButton .fa-arrow-left, .settingsButton .fa-arrow-right, .favsButton .fa-cog, .favsButton .fa-heart, .favsButton .fa-arrow-left, .favsButton .fa-arrow-right { align-items: center; display: flex; height: 100%; justify-content: center; left: calc(50% - 10px); position: absolute; top: 0; width: 100%;
}
.favsMessage { background: rgba(255, 255, 255, 0.4); left: 0; position: absolute; text-align: center;
}
.favorites { margin-bottom: 50px; overflow-x: hidden; overflow-y: scroll; padding-top: 10px; transform: translate3d(7px, 0px, 0px); width: 100%;
}
.favoriteImage { margin-bottom: 10px; overflow: hidden; position: relative; text-align: center; width: 220px; margin: 10px auto;
}
.favoriteImage img { border: 10px solid brown; border-image: url("https://image.freepik.com/free-vector/wood-texture-collection-set_1078-63.jpg") 30 round; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
}
.favoriteImage:hover > .icons { opacity: 1;
}
.favsButton { left: 5px;
}
.favsButton .fa-heart { color: #ff8da1;
}
.canvas { border: 10px solid tan; border-image: url("https://image.freepik.com/free-vector/wood-texture-collection-set_1078-63.jpg") 30 round; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.2);
}

Mondrian Generator - Script Codes JS Codes

"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/*! modernizr 3.5.0 (Custom Build) | MIT * * https://modernizr.com/download/?-inputtypes-setclasses !*/
// Code for checking if color inputs are available in browser, Modernizr.
!function (e, t, n) { function a(e, t) { return (typeof e === "undefined" ? "undefined" : _typeof(e)) === t; }function s() { var e, t, n, s, i, o, c;for (var u in r) { if (r.hasOwnProperty(u)) { if (e = [], t = r[u], t.name && (e.push(t.name.toLowerCase()), t.options && t.options.aliases && t.options.aliases.length)) for (n = 0; n < t.options.aliases.length; n++) { e.push(t.options.aliases[n].toLowerCase()); }for (s = a(t.fn, "function") ? t.fn() : t.fn, i = 0; i < e.length; i++) { o = e[i], c = o.split("."), 1 === c.length ? Modernizr[c[0]] = s : (!Modernizr[c[0]] || Modernizr[c[0]] instanceof Boolean || (Modernizr[c[0]] = new Boolean(Modernizr[c[0]])), Modernizr[c[0]][c[1]] = s), l.push((s ? "" : "no-") + c.join("-")); } } } }function i(e) { var t = u.className, n = Modernizr._config.classPrefix || "";if (f && (t = t.baseVal), Modernizr._config.enableJSClass) { var a = new RegExp("(^|\\s)" + n + "no-js(\\s|$)");t = t.replace(a, "$1" + n + "js$2"); }Modernizr._config.enableClasses && (t += " " + n + e.join(" " + n), f ? u.className.baseVal = t : u.className = t); }function o() { return "function" != typeof t.createElement ? t.createElement(arguments[0]) : f ? t.createElementNS.call(t, "http://www.w3.org/2000/svg", arguments[0]) : t.createElement.apply(t, arguments); }var l = [], r = [], c = { _version: "3.5.0", _config: { classPrefix: "", enableClasses: !0, enableJSClass: !0, usePrefixes: !0 }, _q: [], on: function on(e, t) { var n = this;setTimeout(function () { t(n[e]); }, 0); }, addTest: function addTest(e, t, n) { r.push({ name: e, fn: t, options: n }); }, addAsyncTest: function addAsyncTest(e) { r.push({ name: null, fn: e }); } }, Modernizr = function Modernizr() {};Modernizr.prototype = c, Modernizr = new Modernizr();var u = t.documentElement, f = "svg" === u.nodeName.toLowerCase(), p = o("input"), d = "search tel url email datetime date month week time datetime-local number range color".split(" "), m = {};Modernizr.inputtypes = function (e) { for (var a, s, i, o = e.length, l = "1)", r = 0; o > r; r++) { p.setAttribute("type", a = e[r]), i = "text" !== p.type && "style" in p, i && (p.value = l, p.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(a) && p.style.WebkitAppearance !== n ? (u.appendChild(p), s = t.defaultView, i = s.getComputedStyle && "textfield" !== s.getComputedStyle(p, null).WebkitAppearance && 0 !== p.offsetHeight, u.removeChild(p)) : /^(search|tel)$/.test(a) || (i = /^(url|email)$/.test(a) ? p.checkValidity && p.checkValidity() === !1 : p.value != l)), m[e[r]] = !!i; }return m; }(d), s(), i(l), delete c.addTest, delete c.addAsyncTest;for (var h = 0; h < Modernizr._q.length; h++) { Modernizr._q[h](); }e.Modernizr = Modernizr;
}(window, document);
// IF the color input is not available then the positioning of elements will be changed a bit to accommodate.
if (!Modernizr.inputtypes.color) { fixForEdge(); var colorInputs = document.querySelectorAll('.colorInput'); var colorsSetting = document.querySelector(".colorsSetting"); var settingsButtons = document.querySelector(".settingsButtons"); colorsSetting.style.display = "flex"; colorsSetting.style.flexFlow = "column"; settingsButtons.style.margin = "60px 0 0 0"; Array.prototype.forEach.call(colorInputs, function (input) { input.style.maxWidth = "100px"; });
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var generateButton = document.getElementById("generateButton");
var heartButton = document.querySelector('#heartButton');
var saveIcon = document.querySelector('.save');
var settingsMenu = document.querySelector('.settingsMenu');
var favsMenu = document.querySelector('.favsMenu');
var settingsButton = document.querySelector('#settingsButton');
var resetSettingsButton = document.querySelector("#settingsResetButton");
var favsButton = document.querySelector('#favsButton');
var settingsUpdateButton = document.getElementById("settingsUpdateButton");
var pixelSizeInput = document.getElementById("pixelSizeInput");
var lineCountInput = document.getElementById("lineCount");
var favsMessage = document.querySelector(".favsMessage");
var settingsOpen = false;
var favsOpen = false;
var randomize = true;
var pixelSize = 5;
var lineCount = 30;
var lastSaved = undefined;
var favorited = false;
var favorites = document.querySelector(".favorites");
var colors = ["#008000", "#BF0000", "#E4F7F7", "#0500EF", "#FFF700"];
// inputLimit
/* - This makes sure that the numbers that a user inputs are not too low or too high. Since this is not a form and is not be submitted the default checking with min and max does not work so this is used as a replacement for that.
*/
pixelSizeInput.addEventListener("change", function (e) { return inputLimit(e, 10, 1);
});
lineCountInput.addEventListener("change", function (e) { return inputLimit(e, 50, 3);
});
function inputLimit(e, max, min) { if (e.target.value > max) { e.target.value = max; } else if (e.target.value < min) { e.target.value = min; }
}
// updateSettings
/* - If the update button is pressed in the settings menu this function will be called. It will get the values in the fields and set them so a user can customize how the Mondrian is generated. - randomize might be a little confusing, that is something I decided to use to give more color variation in the mondrian that was generated. I should explain that in the Grid class.
*/
settingsUpdateButton.addEventListener("click", updateSettings);
function updateSettings(e) { pixelSize = pixelSizeInput.value; lineCount = lineCountInput.value; randomize = document.getElementById("randomizeSelect").value == "true" ? true : false; var colorInputs = document.querySelectorAll(".colorInput"); Array.prototype.forEach.call(colorInputs, function (input, i) { colors[i] = input.value; }); toggleSettings(); createGrid();
}
resetSettingsButton.addEventListener("click", resetSettings);
function resetSettings() { randomize = true; pixelSize = 5; lineCount = 30; pixelSizeInput.value = pixelSize; lineCountInput.value = lineCount; document.getElementById("randomizeSelect").value = randomize.toString(); colors = ["#008000", "#BF0000", "#E4F7F7", "#0500EF", "#FFF700"]; var colorInputs = document.querySelectorAll(".colorInput"); Array.prototype.forEach.call(colorInputs, function (input, i) { input.value = colors[i]; });
}
// toggleSettings
/* - This function will toggle the settngs menu as well as close the favs menu if it is open. It will also change the button used to toggle between a back arrow and a cog.
*/
settingsButton.addEventListener("click", toggleSettings);
function toggleSettings() { if (favsOpen) toggleFavs(); settingsOpen = !settingsOpen; if (settingsOpen) { settingsMenu.style.transform = "translate3d(0,0,0)"; settingsButton.firstChild.className = "fa fa-arrow-left"; } else { settingsMenu.style.transform = "translate3d(100%,0,0)"; settingsButton.firstChild.className = "fa fa-cog"; }
}
// toggleFavs
/* - This function will toggle the favs menu as well as close the settings menu if it is open. It will also change the button used to toggle between a back arrow and a heart.
*/
favsButton.addEventListener("click", toggleFavs);
function toggleFavs() { if (settingsOpen) toggleSettings(); favsOpen = !favsOpen; if (favsOpen) { favsMenu.style.transform = "translate3d(0,0,0)"; favsButton.firstChild.className = "fa fa-arrow-right"; loadFavs(); } else { favsMenu.style.transform = "translate3d(-100%,0,0)"; favsButton.firstChild.className = "fa fa-heart"; }
}
// loadFavs
/* - This function is called when the favorites page is opened. It first checks to see if a master keys list exists or if it's empty. - If it's not empty then the function will retrieve the keyes and loop through each one, making a div to hold the image, and creating a mini-menu called "icons" for each image so that the user can either save that image or can delete the image from their favorites. - If the keys list does not exist or is empty then a message will inform the user that they do not have any favorites.
*/
function loadFavs() { if (localStorage.getItem("keys") && JSON.parse(localStorage.getItem("keys")).length != 0) { if (favsMessage.firstChild) { favsMessage.removeChild(favsMessage.firstChild); }; var keys = JSON.parse(localStorage.getItem("keys")); if (favorites.childElementCount != JSON.parse(localStorage.getItem("keys")).length) { while (favorites.firstChild) { favorites.removeChild(favorites.firstChild); } keys.forEach(function (key) { var imageData = localStorage.getItem(new Date(key)); var image = new Image(); image.src = imageData; image.setAttribute("download", "file.png"); var imageContainer = document.createElement("div"); imageContainer.className = "favoriteImage"; imageContainer.id = key; imageContainer.appendChild(image); // icons var icons = document.createElement("div"); icons.className = "icons"; var save = document.createElement("i"); save.className = "icon fa fa-floppy-o"; save.addEventListener("click", function () { window.open(imageData, "thing.png"); }); var del = document.createElement("i"); del.className = "icon fa fa-times"; del.addEventListener("click", function () { localStorage.removeItem(new Date(key)); var keys = JSON.parse(localStorage.getItem('keys')); keys.splice(keys.indexOf(new Date(key)), 1); localStorage.setItem("keys", JSON.stringify(keys)); loadFavs(); }); //appending icons.appendChild(save); icons.appendChild(del); imageContainer.appendChild(icons); favorites.appendChild(imageContainer); }); } } else { // This runs if the user has not favorited any art. while (favorites.firstChild) { favorites.removeChild(favorites.firstChild); } if (!favsMessage.firstChild) { favsMessage.appendChild(document.createTextNode("You currently do not have any favorites! Hover over a generated mondrian to favorite or save it.")); } }
}
// Random event listeners for the icons.
saveIcon.addEventListener("click", function () { canvas.toBlob(function (blob) { saveAs(blob, "mondrian.png"); });
});
heartButton.addEventListener("mouseover", function () { if (!favorited) heartButton.className = "icon fa fa-heart";
});
heartButton.addEventListener("mouseleave", function () { if (!favorited) heartButton.className = "icon fa fa-heart-o";
});
var Grid = function () { function Grid(size, lines, pixelSize, randomize, colors) { _classCallCheck(this, Grid); this.size = size; this.lineCount = lines; this.pixelSize = pixelSize; this.grid; this.lineCoords = []; this.randomize = randomize; this.colors = ["r", "b", "g", "w", "y"]; this.canvasColors = colors; canvas.height = "" + size * pixelSize; canvas.width = "" + size * pixelSize; canvas.style.height = size * pixelSize + "px"; canvas.style.width = size * pixelSize + "px"; canvas.style.maxHeight = size * pixelSize + "px"; canvas.style.maxWidth = size * pixelSize + "px"; } // makeGrid /* - This function initializes the making of the grid. First it creates an ascii grid with arrays inside a main array to make a "3d" array of the dimesions needed. - Once the array is made, lines are then made. - The lines (expecially when randomized is true) create quite a mess of colors so fix grid is there to make sure each box is filled with a specific color. */ Grid.prototype.makeGrid = function makeGrid() { this.grid = new Array(this.size).fill(new Array(this.size).fill("w")); for (var x = 0; x < this.lineCount; x++) { this.makeLines(); } this.fixGrid(); }; // getRandColor /* - This function will exclude a color if it is given. It will then choose a color from the remaining colors and return that color. It uses the classes this.colors array. */ Grid.prototype.getRandColor = function getRandColor(exclude) { var usableColors = exclude ? this.colors.filter(function (x) { return x != exclude; }) : this.colors; var n = Math.floor(Math.random() * usableColors.length); var randColor = usableColors[n].toString(); return randColor; }; // makeLines /* - This function will first get a random direction, either horizontal or vertical. Once it has gotten the direction it will then get a random number from the 2nd row to the 2nd row to the end vertically or horizontally. - For either direction it will check if there is a line already placed on that row in the same direction. It will check if there is a line one row up or down (for horizontal), or to the left or right (for vertical) to this potential new line. If there is then the line will not be draw because it will either be useless or will make an ugly black box. - The first part of code for each direction gives the line a lieele randomeness. So instead of it being drawn from start to finish, each time it comes in contact with another line there is a chance that it will stop being drawn until it encounters another line. This makes the image less uniform making it feel more natural. - Next, for each direction a coordinate of the line is pushed which includes the direction and the row or column number. This it for use mentioned in paragraph two. - Finally, if the direction is horizontal, then all of the pixels above the line are up for question and might be changed. For vertical all pixels to the right are up for question. This is like splitting a red box in half, and to make it look more interesting one half becomes blue and the other remains red. */ Grid.prototype.makeLines = function makeLines() { var _this = this; var dir = ["h", "v"]; var randDir = dir[Math.floor(Math.random() * dir.length)]; var randNum = Math.floor(Math.random() * (this.size - 1 - 1) + 1); var stopped = undefined; if (randDir == "h" && !this.lineCoords.includes("" + randNum + randDir) && !this.lineCoords.includes("" + (randNum - 1) + randDir) && !this.lineCoords.includes("" + (randNum + 1) + randDir)) { (function () { _this.grid[randNum] = _this.grid[randNum].map(function (item, i) { if (item == "o" || i == 0) { var willStop = Math.floor(Math.random() * 2); stopped = willStop ? true : false; } if (!stopped) { item = "o"; } return item; }); _this.lineCoords.push("" + randNum + randDir); var randColor = _this.getRandColor(_this.grid[randNum][1]); for (var row = randNum; row >= 0; row--) { if (_this.randomize) randColor = _this.getRandColor(_this.grid[randNum][1]); _this.grid[row] = _this.grid[row].map(function (item, i) { if (item != "o" && item == _this.grid[randNum + 1][1] && _this.grid[randNum][i] == "o") { item = randColor; } return item; }); } })(); } else if (randDir == "v" && !this.lineCoords.includes("" + randNum + randDir) && !this.lineCoords.includes("" + (randNum - 1) + randDir) && !this.lineCoords.includes("" + (randNum + 1) + randDir)) { (function () { _this.grid.forEach(function (row, i) { if (row[randNum] == "o" || i == 0) { var willStop = Math.floor(Math.random() * 2); stopped = willStop ? true : false; } if (!stopped) { row[randNum] = "o"; } }); _this.lineCoords.push("" + randNum + randDir); var randColor = _this.getRandColor(); _this.grid.forEach(function (row, y) { if (_this.randomize) randColor = _this.getRandColor(); for (var i = randNum; i >= 0; i--) { if (row[i] != "o" && row[i] == _this.grid[1][randNum + 1]) { row[i] = randColor; } } }); })(); } // For logging images of the drawing of the canvas. // this.logImage(); this.draw(); }; // logImages /* - This is a function that helps debugging by console logging images of the canvas at a current point. It also has some other logging for other debugging. */ Grid.prototype.logImage = function logImage() { var dataURL = canvas.toDataURL(); console.log('%c', "background: url('" + dataURL + "'); width: 150px; line-height: 150px; text-align: center; padding: 75px; padding-bottom: 60px"); console.log('%c', "width: 150px; line-height: 150px; text-align: center; padding: 150px"); console.log(this.lineCoords); }; Grid.prototype.fixGrid = function fixGrid() { var _this2 = this; // On the x axis sometimes a color gets cut off due to a bug caused by the possibility that a line on the x axis might not go all the way through. This fixes any visual issues with that. Going left to right the right pixel will become the same color as the left pixel if the left pixel is not a wall and the right pixel is a different color. Same with top to bottom where bottom takes color of top. //Horizontal this.grid = this.grid.map(function (row) { var lastColor = undefined; row = row.map(function (item, i) { if (lastColor != item && lastColor != undefined && lastColor != "o" && item != "o") { item = lastColor; } lastColor = item; return item; }); return row; }); //Vertical var _loop = function _loop(i) { var lastColor = undefined; _this2.grid = _this2.grid.map(function (row) { if (lastColor != row[i] && lastColor != undefined && lastColor != "o" && row[i] != "o") { row[i] = lastColor; } lastColor = row[i]; return row; }); }; for (var i = 0; i < this.grid.length; i++) { _loop(i); } }; // draw /* - draw will go through each index in the grid and draw the color that it was in ascii onto the actual canvas in that color. Nothing too special here. */ Grid.prototype.draw = function draw() { var _this3 = this; //console.log(this.grid); this.grid.forEach(function (row, y) { row.forEach(function (item, x) { switch (item) { case "g": ctx.fillStyle = _this3.canvasColors[0]; break; case "r": ctx.fillStyle = _this3.canvasColors[1]; break; case "o": ctx.fillStyle = "black"; break; case "w": ctx.fillStyle = _this3.canvasColors[2]; break; case "b": ctx.fillStyle = _this3.canvasColors[3]; break; case "y": ctx.fillStyle = _this3.canvasColors[4]; break; } ctx.fillRect(x * _this3.pixelSize, y * _this3.pixelSize, _this3.pixelSize, _this3.pixelSize); }); }); }; return Grid;
}();
// createGrid
/* - This function will first set favorited to false since it is a new mondrian. It will then generate the new mondrian and draw it out. - Since favorited is false the "heartButton" should just be an outline.
*/
generateButton.addEventListener("click", createGrid);
function createGrid() { favorited = false; var art = new Grid(Math.floor(200 / pixelSize), lineCount, pixelSize, randomize, colors); art.makeGrid(); art.draw(); heartButton.className = "icon fa fa-heart-o";
}
createGrid();
// favoriteArt
/* - This function will favorite a mondrian if it hasn't been favorited already. It will then take the data of the image and place it into local storage with a key as the timestamp it was favorited. This key will also be added to a master list containing all the keys of favorited pieces. - If the mondrian has already been favorited then it will remove ht piece from localStorage and remove the key associated with it from the master keys list. - Favoriting and unfavoriting will also toggle the "hearButton" so it is either filled in or just an outline.
*/
heartButton.addEventListener("click", favoriteArt);
function favoriteArt() { if (!favorited) { heartButton.className = "icon fa fa-heart"; var dataUrl = canvas.toDataURL(); var key = new Date(); lastSaved = key; localStorage.setItem(key, dataUrl); var keys = JSON.parse(localStorage.getItem('keys')) || []; keys.push(key); localStorage.setItem("keys", JSON.stringify(keys)); } else { heartButton.className = "icon fa fa-heart-o"; localStorage.removeItem(lastSaved); var keys = JSON.parse(localStorage.getItem('keys')); keys.splice(keys.indexOf(lastSaved), 1); localStorage.setItem("keys", JSON.stringify(keys)); } favorited = !favorited;
}
// A bunch of code for fixing the main functionality in Edge.
function fixForEdge() { /* canvas-toBlob.js * A canvas.toBlob() implementation. * 2016-05-26 * * By Eli Grey, http://eligrey.com and Devin Samarin, https://github.com/eboyjr * License: MIT * See https://github.com/eligrey/canvas-toBlob.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/canvas-toBlob.js/blob/master/canvas-toBlob.js */ (function (view) { "use strict"; var Uint8Array = view.Uint8Array, HTMLCanvasElement = view.HTMLCanvasElement, canvas_proto = HTMLCanvasElement && HTMLCanvasElement.prototype, is_base64_regex = /\s*;\s*base64\s*(?:;|$)/i, to_data_url = "toDataURL", base64_ranks, decode_base64 = function decode_base64(base64) { var len = base64.length, buffer = new Uint8Array(len / 4 * 3 | 0), i = 0, outptr = 0, last = [0, 0], state = 0, save = 0, rank, code, undef; while (len--) { code = base64.charCodeAt(i++); rank = base64_ranks[code - 43]; if (rank !== 255 && rank !== undef) { last[1] = last[0]; last[0] = code; save = save << 6 | rank; state++; if (state === 4) { buffer[outptr++] = save >>> 16; if (last[1] !== 61 /* padding character */) { buffer[outptr++] = save >>> 8; } if (last[0] !== 61 /* padding character */) { buffer[outptr++] = save; } state = 0; } } } // 2/3 chance there's going to be some null bytes at the end, but that // doesn't really matter with most image formats. // If it somehow matters for you, truncate the buffer up outptr. return buffer; }; if (Uint8Array) { base64_ranks = new Uint8Array([62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51]); } if (HTMLCanvasElement && (!canvas_proto.toBlob || !canvas_proto.toBlobHD)) { if (!canvas_proto.toBlob) canvas_proto.toBlob = function (callback, type /*, ...args*/) { if (!type) { type = "image/png"; }if (this.mozGetAsFile) { callback(this.mozGetAsFile("canvas", type)); return; }if (this.msToBlob && /^\s*image\/png\s*(?:$|;)/i.test(type)) { callback(this.msToBlob()); return; } var args = Array.prototype.slice.call(arguments, 1), dataURI = this[to_data_url].apply(this, args), header_end = dataURI.indexOf(","), data = dataURI.substring(header_end + 1), is_base64 = is_base64_regex.test(dataURI.substring(0, header_end)), blob; if (Blob.fake) { // no reason to decode a data: URI that's just going to become a data URI again blob = new Blob(); if (is_base64) { blob.encoding = "base64"; } else { blob.encoding = "URI"; } blob.data = data; blob.size = data.length; } else if (Uint8Array) { if (is_base64) { blob = new Blob([decode_base64(data)], { type: type }); } else { blob = new Blob([decodeURIComponent(data)], { type: type }); } } callback(blob); }; if (!canvas_proto.toBlobHD && canvas_proto.toDataURLHD) { canvas_proto.toBlobHD = function () { to_data_url = "toDataURLHD"; var blob = this.toBlob(); to_data_url = "toDataURL"; return blob; }; } else { canvas_proto.toBlobHD = canvas_proto.toBlob; } } })(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this); // includes polyfill for edge. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes if (!Array.prototype.includes) { Object.defineProperty(Array.prototype, 'includes', { value: function value(searchElement, fromIndex) { // 1. Let O be ? ToObject(this value). if (this == null) { throw new TypeError('"this" is null or not defined'); } var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If len is 0, return false. if (len === 0) { return false; } // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undefined, this step produces the value 0.) var n = fromIndex | 0; // 5. If n ≥ 0, then // a. Let k be n. // 6. Else n < 0, // a. Let k be len + n. // b. If k < 0, let k be 0. var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); function sameValueZero(x, y) { return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y); } // 7. Repeat, while k < len while (k < len) { // a. Let elementK be the result of ? Get(O, ! ToString(k)). // b. If SameValueZero(searchElement, elementK) is true, return true. // c. Increase k by 1. if (sameValueZero(o[k], searchElement)) { return true; } k++; } // 8. Return false return false; } }); }
}
Mondrian Generator - Script Codes
Mondrian Generator - Script Codes
Home Page Home
Developer Devin
Username edwin0258
Uploaded November 23, 2022
Rating 3.5
Size 21,771 Kb
Views 12,144
Do you need developer help for Mondrian Generator?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Devin (edwin0258) Script Codes
Create amazing captions with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!