JSFiddle - React, Tailwind, and code Playground
by kouty79
HTML
<canvas id="canvas" width="240" height="320"></canvas>
CSS
#canvas {
border: 1px solid black;
}
JavaScript
const path = [
{id:1, tipo: 'rettilineo',length:3,width:3},
{id:2, tipo: 'rettilineo',length:2,width:3},
{id:3, tipo: 'rettilineo',length:1,width:3},
{id:4, tipo: 'curva_dx',angolo:45, raggio:5,width:3},
{id:5, tipo: 'rettilineo',length:1,width:3},
{id:6, tipo: 'curva_up',angolo:25, raggio:5,width:3},
{id:7, tipo: 'rettilineo',length:2,width:3},
{id:8, tipo: 'curva_down',angolo:25, raggio:5,width:3},
{id:9, tipo: 'rettilineo',length:1,width:3},
{id:10, tipo: 'curva_sx',angolo:20, raggio:10,width:3},
{id:11, tipo: 'curva_down',angolo:25, raggio:5,width:3},
{id:12, tipo: 'rettilineo',length:2,width:3},
{id:13, tipo: 'curva_up',angolo:25, raggio:5,width:3},
{id:14, tipo: 'rettilineo',length:1,width:3},
{id:15, tipo: 'rettilineo',length:1,width:3}
];
let pivot = {x:0, y:0, angle: 0};
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'blue';
ctx.translate(160, 0);
const zoom = 10;
path.forEach((element)=>{
let delta = {x:0, y:0, angle:0};
let figure;
let width = element.width;
let len;
switch(element.tipo) {
case 'curva_sx':
delta.angle = -degToRad(element.angolo);
case 'curva_dx':
delta.angle = delta.angle || degToRad(element.angolo);
len = element.raggio;
delta.x = -element.raggio * zoom * Math.sin(pivot.angle+delta.angle);
delta.y = element.raggio * zoom * Math.cos(pivot.angle+delta.angle);
figure = arc(delta.angle, len, width);
//figure = rotate(figure, delta.angle);
break;
case 'rettilineo':
len = element.length;
default:
len = len || 1;
delta.x = -len * zoom * Math.sin(pivot.angle);
delta.y = len * zoom * Math.cos(pivot.angle);
figure = rect(len, width);
}
draw(translate(rotate(figure, pivot.angle), pivot));
pivot.x += delta.x;
pivot.y += delta.y;
pivot.angle += delta.angle;
});
function arc(angle, radius, width) {
const w = width * zoom;
const r = radius *...