Canvas How to - Link lines to create shape








Question

We would like to know how to link lines to create shape.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--from   w  w w.j  a va2s.  co  m-->
    ctx = document.getElementById('cnv').getContext('2d');
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.lineWidth = 10;
    ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)';
    ctx.beginPath();
    ctx.moveTo(50, 100);
    ctx.lineTo(250, 100);
    ctx.lineTo(250, 250);
    ctx.lineTo(100, 250);
    ctx.lineTo(100, 50);
    ctx.lineTo(150, 50);
    ctx.lineTo(150, 200);
    ctx.lineTo(200, 200);
    ctx.lineTo(200, 150);
    ctx.lineTo(50, 150);
    ctx.lineTo(50, 100);
    ctx.closePath();
    ctx.stroke();
    ctx.strokeStyle = 'rgba(0, 255, 0, 0.5)';
    ctx.beginPath();
    ctx.moveTo(50, 250);
    ctx.lineTo(250, 50);
    ctx.closePath();
    ctx.stroke();
}//]]>  
</script>
</head>
<body>
  <canvas id="cnv" width="300" height="300"></canvas>
</body>
</html>

The code above is rendered as follows: