Canvas How to - Draw Polygon








Question

We would like to know how to draw Polygon.

Answer


<!--from   w w w .  ja  v  a2s.c o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
    var $canvas = document.getElementsByTagName('canvas');
    if ($canvas[0].getContext) {
        var context = $canvas[0].getContext('2d');
        context.fillStyle = 'red';
        context.beginPath();
        context.moveTo(0,0);
        context.lineTo(100,100);
        context.lineTo(50,100);
        context.lineTo(40,110);
        context.lineTo(90,110);
        context.lineTo(-10,10);
        context.lineTo(0,0);
        context.stroke();
        context.fill();
    }
}//]]>  
</script>
</head>
<body>
  <canvas width="300" height="300"></canvas>
</body>
</html>

The code above is rendered as follows: