Canvas How to - Fill a triangle in animation








Question

We would like to know how to fill a triangle in animation.

Answer


<!--from  w  w  w. ja v  a 2  s  . c o  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById("canvasWindow");
var c = canvas.getContext("2d");
var startX = 10;
var startY = 10;
var midX = 75;
var midY = 175;
var endX = 175;
var endY = 50;
var amount = 0;

function drawLine2() {
    amount += 0.009;
    if (amount > 1) amount = 1;
    c.clearRect(0, 0, canvas.width, canvas.height);
    c.moveTo(startX, startY);
    c.lineTo(midX + (endX - midX) * amount, midY + (endY - midY) * amount);
    c.strokeStyle = "blue";
    c.lineWidth = 3;
    c.stroke();
}
setInterval(drawLine2, 30);
}//]]>  
</script>
</head>
<body>
  <canvas id="canvasWindow" width="200" height="200">
</canvas>
</body>
</html>

The code above is rendered as follows: