HTML5 Game - Drawing Paths with Lines

Introduction

The simplest paths are those made up of straight lines.

The following code shows how to create a path from straight-lines.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black}
            body > * {float:left;}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="500" height="140">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
       //from  ww w  .  ja  v a2  s  . c o  m
            ctx.fillStyle = "yellow";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 4;
       
            ctx.beginPath();
            ctx.moveTo(10, 10);
            ctx.lineTo(110, 10);
            ctx.lineTo(110, 120);
            ctx.closePath();
            ctx.fill();
            
            ctx.beginPath();
            ctx.moveTo(150, 10);
            ctx.lineTo(200, 10);
            ctx.lineTo(200, 120);
            ctx.lineTo(190, 120);
            
            ctx.fill();
            ctx.stroke();
            
            ctx.beginPath();
            ctx.moveTo(250, 10);
            ctx.lineTo(250, 120);
            ctx.stroke();
        </script>
    </body>
</html>

Related Topic