Skip to content

Instantly share code, notes, and snippets.

@vertighel
Last active May 21, 2018 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vertighel/4965462 to your computer and use it in GitHub Desktop.
Save vertighel/4965462 to your computer and use it in GitHub Desktop.
svg labels with saving button

Simple Form to add text elements to an svg image, inspired by a duopixel example. The number of the elements are defined by a simple text array. The text of the array elements will be used to set IDs and classes.

Clicking on the link will download the svg image (tested on Chromium, Firefox and Opera).

Comments in Italian language.

<!doctype html>
<title>Elemental dadi</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap.css, jquery, popper, bootstrap.js -->
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="./node_modules/jquery/dist/jquery.min.js"></script>
<script src="./node_modules/popper.js/dist/umd/popper.min.js"></script>
<script src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- d3 -->
<script src="./node_modules/d3/build/d3.min.js"></script>
<!-- ws_protocol -->
<!-- <script src="./node_modules/ws_protocol_layer/lib/common/event.js"></script> -->
<!-- <script src="./node_modules/ws_protocol_layer/lib/common/ws.js"></script> -->
<!-- <script src="./node_modules/ws_protocol_layer/lib/web/ws_client.js"></script> -->
<style>
/* Generated using sass --watch style.scss:style.css */
/* @import url("./style.css"); */
</style>
<body lang="en">
<main class="container">
<h1>lancio dadi Elemental</h1>
<form class="form">
<div class="form-group form-row">
<div class="input-group col">
<div class="input-group-prepend">
<label class="input-group-text" for="perso">Personaggio</label>
</div>
<select class="custom-select" id="perso">
<!-- questa parte verrà popolata con i nomi dei personaggi -->
</select>
</div>
</div>
<div class="form-group form-row">
<p class="form-text col-sm-2">Bonus / Malus </p>
<div id="bonusmalus" class="btn-group btn-group-toggle col-sm" data-toggle="buttons">
<!-- <label class="btn btn-primary active"> -->
<!-- <input type="radio" name="boma" id="bomaX" autocomplete="off" checked> Active -->
<!-- </label> -->
</div>
</div>
<div class="form-group form-row">
<label class="form-text col-sm-2" for="pulsanti">Lancia un D20 su</label>
<div id="pulsanti" class="btn-group col-sm" role="group">
<!-- questa parte verrà popolata con i pulsanti relativi alle capacità-->
</div>
</div>
</form>
<article class="row">
<section class="col-sm">
<dl>
<!-- questa parte verrà popolata con i punti di ogni capacità -->
</dl>
<strong>Risultato di base +bonusmalus +D20: </strong> <var><!-- qui viene fuori il risultato --></var>
</section>
<figure class="col-sm">
</figure>
</article>
<script>
var personaggi=[
{
nome: "Helium",
fisico: 11,
mente: 22,
controllo: 33,
},
{
nome: "Moth",
fisico: 44,
mente: 55,
controllo: 66,
},
{
nome: "Cobalt",
fisico: 77,
mente: 88,
controllo: 99,
},
]
//var bonusmalus= ["aaaaaa", "bbbbb", "ccccc", "dddddd", "eeeee"]
var bonusmalus= [-2, -1, 0, +1, +2]
//////////// Popolo il form /////////////////
var form = d3.select("form")
/// Appendo la lista dei personaggi
var select = d3.select('select')
.on('change',onchange)
var options = select
.selectAll('option')
.data(personaggi).enter()
.append('option')
.attr('value',function(d,i){return i})
.text(function(d){return d.nome});
/// Appendo la lista di bonus e malus
var radio = d3.select('#bonusmalus')
// .on('change',onchange)
var rad = radio
.selectAll('label')
.data(bonusmalus).enter()
.append('label')
// .attr('class','btn btn-primary col')
.attr('class',function(d){return d==0 ? 'btn btn-primary col active' : 'btn btn-primary col'})
.text(function(d){return d})
.append('input')
.attr('type','radio')
.attr('name','boma')
.attr('checked',function(d){return d==0 ? 'checked' : null})
.attr('autocomplete','off')
.attr('id', function(d){return "boma"+d})
.attr('value',function(d){return d})
/// Appendo i bottoni
var dummy0 = Object.assign({}, personaggi[0]) /// prendo il primo personaggio per avere la lista dei valori
delete dummy0.nome; /// taglio il nome per ottenere solo fisico, mente, controllo
var entry0= d3.entries(dummy0) /// [{key: "fisico", value: 0}, {key: "mente", value: 0} etc.]
var pulsanti = d3.select("#pulsanti")
var buttons = pulsanti
.selectAll('button')
.data(entry0).enter()
.append('button')
.attr('type','button')
.attr('class','btn btn-primary col')
.text(function(d){return d.key})
.on('click',onclick)
// Appendo la lista delle caratteristiche
var dl= d3.select("dl")
onchange() /// chiamo almeno una volta la funzione per ottenere una lista iniziale
/// ogni volta che un personaggio viene selezionato, mostra le sue caratteristiche
function onchange() {
selezionato = d3.select('select').property('value')
var entries = d3.entries(personaggi[selezionato])
dl.html( new Array(entries.length + 1).join("<dt/><dd/>") );
dl.selectAll("dt").data(entries).html(function(d) { return d.key; });
dl.selectAll("dd").data(entries).html(function(d) { return d.value; });
};
/// ogni volta che un pulsante viene cliccato lancia un dado e mostra il risultato su quella caratteristica
function onclick() {
selezionato = d3.select('select').property('value') /// id Helium = 0
caratteristica = d3.select(this).datum() /// {key: "fisico", value: 0}
var base = personaggi[selezionato][caratteristica.key] /// personaggi['helium'].fisico = 0
var dado = getRandomInt(1,20) /// Tiro un D20 (intero random da 1 a 20)
var boma = parseInt(d3.select('input[name="boma"]:checked').node().value)
d3.select('var')
.text(base+" "+ ((boma<0?"":"+")+boma) +" +"+dado+" = "+ (base+boma+dado) ) /// scrive il risultato
};
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
// return personaggi.find(item => {
// return item.restaurant.food == 'chicken'
// })
// var fontsize=30;
// // margini, larghezza ed altezza dell'immagine svg (in pixel)
// var margin = {top: 30, right: 20, bottom: 30, left: 20},
// width = 400 - margin.left - margin.right,
// height = 200 - margin.top - margin.bottom;
// //////////// Creo la svg /////////////////
// var svg = d3.select("figure").append("svg")
// .attr("xmlns", "http://www.w3.org/2000/svg") // giusto per essere puntigliosi
// .attr("width", width + margin.left + margin.right) // imposto larghezza
// .attr("height", height + margin.top + margin.bottom) // e altezza
// .append("g") // creo un gruppo e lo traslo del valore dei margini
// .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// //////////// Creo i nodi di testo vuoti /////////////////
// svg.selectAll("text") // per ogni nodo di testo che creerò
// .data(personaggi).enter() // ci attacco i dati
// .append("text") // appendo un nodo di testo
// .attr("class", function(d){return d.nome}) // ognuno con la sua classe presa dal vettore
// .attr("x",0) // posizione in x (in pixel)
// .attr("y",function(d,i){ return height/dati.length*i+fontsize}) // non è proprio perfetto come allineamento..
// .attr({ // un altro modo per impostare gli attibuti, magari costanti, tutti assieme invece che uno per uno
// "font-size": fontsize, // non lo faccio nel css perché sennò non vengono esportati
// "font-family": "Helvetica"
// })
// //////////// Ci metto il testo dinamicamente /////////////////
// d3.selectAll("input").on("keyup",function(){ // ogni volta che schiaccio un tasto...
// var cls=d3.select(this).attr("class") // mi segno la sua classe (class="cognome")
// var val=d3.select(this).property("value") // mi segno il suo valore (amendolia)
// d3.select("text."+cls).text(val) // imposto il testo al nodo di testo che ha la stessa clase
// // creo il nome del file della forma nome-cognome.svg
// var nomecognome=d3.selectAll("text")[0][0].textContent+"-"+d3.selectAll("text")[0][1].textContent+".svg"
// d3.select("a")
// .text("scarica come "+ nomecognome)
// .attr("download", nomecognome) // ci attacco il nuovo attributo download e il nome del file
// })
// //////////// Creo il link per lo scaricamento /////////////////
// d3.select("section a").on("click", function(){ // seleziono la tag <a>, e al click...
// d3.select(this) // ...prendo la tag e ci attacco (penso) il suo contenuto trasformato in bit
// .attr("href", 'data:application/octet-stream;base64,' + btoa(d3.select("figure").html()))
// })
</script>
{
"name": "etichette",
"version": "1.0.0",
"description": "Simple Form to add text elements to an svg image, inspired by a [duopixel example](http://bl.ocks.org/duopixel/3831266). The number of the elements are defined by a simple text array. The text of the array elements will be used to set IDs and classes.",
"main": "index.js",
"dependencies": {
"bootstrap": "^4.1.1",
"d3": "^4.13.0",
"jquery": "^3.3.1",
"popper.js": "^1.14.3"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://gist.github.com/4965462.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://gist.github.com/4965462"
},
"homepage": "https://gist.github.com/4965462"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment