<div class="container">
<h4>Enter whole number to generate the graph</h4>
<p>Does not support large numbers yet.</p>
<canvas id="canvas" width="500" height="300"/>
</div>
<div class="form">
<input id="num" type="number" step="1" min="1" value="32" class="take-number">
<button id="calc">Generate</button>
takes <span id="show"></span> steps
</div>
body {background-color:#1d1f20;}
.container{
width: 100%;
text-align: center;
margin-top: 30px;
}
p, h4, h6{
color: white;
}
.form {
margin-top: 20px;
text-align: center;
color: white;
}
.take-number {
background: white;
position: relative;
}
#calc {
margin-right: 10px;
}
// forked from here https://codepen.io/mr_brunocastro/pen/GJRqJa
function init() {
var show = document.getElementById('show');
var button = document.getElementById('calc');
button.addEventListener('click', function(){
calculate();
});
}
var valores = [32,16,8,4,2,1];
var pontos = [];
var diferenca =[];
setInterval(draw,30);
show.innerHTML = valores.length -1 ;
function calculate(){
valores=[];
let num = document.getElementById('num').value;
num = parseInt(num);
num = Math.floor(num);
let step = 0;
console.log(num);
while(num>1){
step = step + 1;
if(num%2 == 0){
num = num/2;
}else{
num = num*3 +1;
}
valores.push(num);
}
show.innerHTML = step;
console.log(valores);
setInterval(draw,30);
}
//////////////// Variáveis // Valores aqui!
function drawGrid(width,height,colun,line) {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillRect(0,0,width,height);
ctx.save();
for (var c=1; c<(width/colun); c++) {
ctx.beginPath();
ctx.moveTo(c*colun,0);
ctx.lineTo(c*colun,height);
ctx.stroke();
}
for (var l=1; l<(height/line); l++) {
ctx.beginPath();
ctx.moveTo(0,l*line);
ctx.lineTo(width, l*line);
ctx.stroke();
}
}
function drawingLines (width,points,c) {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.beginPath();
ctx.globalAlpha = c*0.04;
ctx.moveTo(((c-1)*width+10),points[c-1]);
ctx.lineTo(c*width+10,points[c]);
ctx.lineTo(c*width+10,300);
ctx.lineTo(((c-1)*width+10),300);
ctx.lineTo(((c-1)*width+10),points[c-1]);
ctx.fill();
ctx.beginPath();
ctx.globalAlpha = 1;
ctx.moveTo(((c-1)*width+10),points[c-1]);
ctx.lineTo(c*width+10,points[c]);
ctx.stroke();
ctx.beginPath();
ctx.save();
ctx.fillStyle=ctx.strokeStyle;
ctx.arc(c*width+10,points[c],3,0,Math.PI*2)
ctx.fill();
ctx.restore();
}
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
//////////////// setupBackground
ctx.fillStyle ="#1d1f20";
ctx.strokeStyle ="#333";
ctx.save();
drawGrid(500,300,10,10);
for (var c=0; c<valores.length; c++) {
if(isNaN(pontos[c])){
pontos[c]=300;
}
ctx.lineWidth=1.4;
larg=480/(valores.length -1);
diferenca[c]=(300-valores[c])-pontos[c];
pontos[c]+=diferenca[c]/(c+1);
//////////////// setupGraphic
ctx.strokeStyle ="#0ff";
ctx.fillStyle="#0ff";
drawingLines (larg,pontos,c);
}
}
window.onload = init();
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.