I've been working on a chunk of code for a would-be Sierpinski fractal animation, but for some reason, the animation part just doesn't seem to work. I also tried using setInterval(), with the same results, namely a blank canvas. The idea is to draw an equilateral triangle with vertex coordinates as parameters step by step, as though somebody was drawing it on a piece of paper. Could you have a look to see what's wrong with it?
On a side note, I've copied a few examples of canvas animation off a few web tutorials, and none of them appear to be working in my files either. I use Firefox and Chrome, both up to date, so I guess it's not a technical issue.
<!DOCTYPE html>
<style>
canvas {
width: 600px;
height: 600px;
text-align: center;
background-color: white;
background-position: center;
position: relative;
top: 0px;
left: 0px;
border:1px solid #d3d3d3;
}
<body>
<canvas id="sCanvas"></canvas>
<script>
This is where the animation is supposed to take place; draws a line from (Ax,Ay) to (Bx,By).
function lineAnimation(x1,y1,x2,y2,ctx) {
var deltaX = (x2 - x1) / 100;
var deltaY = (y2 - y1) / 100;
var x = x1;
var y = y1;
var timer = setInterval(function () {
ctx.moveTo(x,y);
ctx.lineTo(x+deltaX,y+deltaY);
ctx.stroke();
x += deltaX;
y += deltaY;
}, 100);
if ((x===x2) && (y===y2)) clearTimeout(timer);
}
function drawTriangle(Ax,Ay,Bx,By,Cx,Cy,ctx) {
lineAnimation(Ax,Ay,Bx,By,ctx);
lineAnimation(Bx,By,Cx,Cy,ctx);
lineAnimation(Cx,Cy,Ax,Ay,ctx);
}
function init() {
var canvas=document.getElementById("sCanvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
drawTriangle(10,10,30,50,50,10);
}
init();
</script>