D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
jfourmond
Full window
Github gist
Keyboard
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v5.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> const svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500); const colorPressed = d3.color("black"); colorPressed.opacity = 0.8; let data = null; d3.json("keys.json") .then((loaded) => { data = loaded; draw(); }) function draw() { const rows = svg.selectAll('.row') .data(data) .enter() .append('g') .attr("class", "row") .attr("transform", (d, i) => "translate(" + (10 * i) + "," + (10 + (45 * i)) + ")"); const keys = rows.selectAll('.key') .data((d) => d) .enter() .append('g') .attr("class", "key") .attr("transform", (d, i) => { return "translate(" + (10 + (45 * i)) + ", 0)"; }); keys.append("rect") .attr("width", 40) .attr("height", 40) .attr("fill", "None") .attr("stroke", "black") .attr("rx", 5) .attr("ry", 5); keys.append("text") .attr("x", 5) .attr("y", 20) .attr("font-size", " 20px") .text((d, i) => d.toUpperCase()); } function keyDownBinding(event) { if (event.defaultPrevented) return; console.log(event.key + ' +'); const sel = d3.selectAll('.key').filter(function() { return d3.select(this).select('text').text() === event.key.toUpperCase(); }); sel.select("rect").attr("fill", colorPressed); sel.select("text").attr("fill", "white"); event.preventDefault(); } function keyUpBinding(event) { if (event.defaultPrevented) return; console.log(event.key + ' -'); const sel = d3.selectAll('.key').filter(function() { return d3.select(this).select('text').text() === event.key.toUpperCase(); }); sel.select("rect").attr("fill", "none"); sel.select("text").attr("fill", "black"); event.preventDefault(); } document.body.addEventListener("keydown", keyDownBinding, true); document.body.addEventListener("keyup", keyUpBinding, true); </script> </body>
https://d3js.org/d3.v5.min.js