D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ocarneiro
Full window
Github gist
Atari 2600 playfield editor
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } #text_area { text-align: center; } </style> </head> <body> <div id="svg_area"></div> <div id="text_area"> <textarea id="playfield_text" cols=40 rows=15> XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX............................XX X...XXXX.XXXX.X...X.XXXX.......X X...X....X..X.XX.XX.X..........X XX..X.XX.XXXX.X.X.X.XXX.......XX X...X..X.X..X.X...X.X..........X X...XXXX.X..X.X...X.XXXX.......X XX............................XX X..............................X X..............................X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </textarea> </div> <script> const PIXEL_SIZE = 20; const FIELD_HEIGHT = 11; const FIELD_WIDTH = 32; var squares = generatePixelDataStructure(); var svg = d3.select("#svg_area").append("svg") .attr("width", 960) .attr("height", 250) .on("click", clicked); var textinarea = document.getElementById('playfield_text'); var singlelinetext = textinarea.value.replace(/(\r\n|\n|\r)/gm,""); //textinarea.value = ""; drawSquares(singlelinetext); function drawSquares(data) { for (var i = 0; i< squares.length; i++) { svg.append("rect") //.attrs({ x: 10, y: 10, width: 80, height: 80, fill: 'red' }) .attr("x", squares[i]["x"]*PIXEL_SIZE) .attr("y", squares[i]["y"]*PIXEL_SIZE) .attr("height", PIXEL_SIZE) .attr("width", PIXEL_SIZE) .attr("fill", (data[i] == "X"? "red" : "black")) } } function generatePixelDataStructure() { var squares = []; for (var r = 0; r < FIELD_HEIGHT; r++) { for (var c = 0; c < FIELD_WIDTH; c++) { squares.push({"x": c, "y": r, "value": 1 }); } } return squares; } function clicked() { var coords = d3.mouse(this); var x = Math.floor(coords[0] / PIXEL_SIZE); var y = Math.floor(coords[1] / PIXEL_SIZE); var pos = y * FIELD_WIDTH + x; var curr_value = singlelinetext[pos]; console.log(x,",", y, "=", curr_value); var new_value = (curr_value == "X" ? "." : "X"); var new_text = singlelinetext.substring(0,pos) + new_value + singlelinetext.substring(pos+1) textinarea.value = addLineBreaks(new_text); drawSquares(new_text); singlelinetext = new_text; } function addLineBreaks(text) { text = text.replace(/(\r\n|\n|\r)/gm,""); new_text = ""; for (var i = 0; i < text.length; i++) { // appends current character to new text new_text = new_text + text[i]; // if it should be the end of this line // adds a line break to it if ((i+1) % FIELD_WIDTH == 0) { new_text = new_text + "\n"; } } return new_text; } </script> </body>
https://d3js.org/d3.v4.min.js