I Canvas di Html5 servono per disegnare sulle pagine web e sono molto semplici da usare, basta inserirne uno nel codice html
<canvas id="myCanvas" width="200" height="100"></canvas>
e poi tramite Javascript disegnare qualcosa, per esempio una linea:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.strokeStyle = "#ff0000";
ctx.lineTo(100,100);
ctx.stroke();
ma se invece volessimo disegnare la linea “lentamente” animandola? Dopo giorni di ricerche convulse su Google ho scoperto che questa funzionalità è presente nel comando “animate” di SVG (l’alternativa ai Canvas ma non supportata da tutti i browser).
L’unica soluzione trovata è costruirsi la funzione da soli usando un po’ di geometria analitica e rispolverando qualche formula di matematica.
MOSTRA IL CODICE….
<script type="text/javascript">
function DistanzaAB(x0, y0, x1, y1)
{
//SQRT( (x1-x0)^2 + (y1-y0)^2 );
return (Math.sqrt(Math.pow(x1-x0, 2)+Math.pow(y1-y0, 2)));
}
function newy(xc , x1, y1, x2, y2)
{
return ((y2-y1)/(x2-x1)*(xc-x1)+y1);
}
function CoeffAng(x0, y0, x1, y1)
{
return (y1-y0)/(x1-x0);
}
function GCoord(a,b)
{
return coords[a][b];
}
$(function(){
c=document.getElementById("myCanvas");
ctx=c.getContext("2d");
coords = [[108,182],[57,150],[60,80],[107,112]];
cont = 1;
cx = GCoord(0,0);
cy = GCoord(0,1);
verso=1;
ctx.moveTo(cx,cy);
drawLine();
});
function drawLine()
{
if (cont<coords.length)
{
var startx = GCoord(cont-1,0);
var starty = GCoord(cont-1,1);
var tox = GCoord(cont,0);
var toy = GCoord(cont,1);
step = (Math.abs(startx-tox) / 10);
//oppure usando DistanzaAB()
if (tox>startx){
verso=step;
cx = (((cx+verso)<=tox))?cx+verso:tox;
}
else {
verso=-1 * step;
cx = (((cx+verso)<=tox))?tox:cx+verso;
}
cy = newy(cx,startx,starty,tox,toy);
ctx.lineTo(cx,cy);
ctx.strokeStyle = "#404040";
ctx.lineCap = "round";
ctx.lineWidth = 1;
ctx.stroke();
if (verso>0)
cond = (cx<tox);
else
cond = (cx>tox);
if (cond){
setTimeout(function(){drawLine()},55);
}
else{
cont = cont+1;
cx = GCoord(cont-1,0);
setTimeout(function(){drawLine()}, 70);
}
}
else
{
//fine procedura
}
}
</script>
In effetti continuando a cercare su Google una soluzione (parziale) al problema l’ho trovata, questa fantastica libreria http://ocanvas.org/ di Johannes Koggdal che ha un unico limite: non permette l’animazione di proprietà di tipo oggetto… cmq un lavoro notevole!