Path2D object example: Simple shapes

An example of using the Path2D object to create simple shapes.

«Back to the Path2D object article

This is an example of creating a set of simple shapes using the Path2D object.

[No canvas support]
<script>
    // Use the jQuery ready() function
    $(document).ready(function ()
    {
        var canvas  = document.getElementById('cvs')
        var context = canvas.getContext('2d');
        
        // A circle
        var path1 = new Path2D();
        path1.arc(100,100,50, 0, Math.PI * 2, false)
        
        // A square
        var path2 = new Path2D();
        path2.rect(200,100,100,100);
        
        // An ellipse
        var path3 = new Path2D();
        path3.ellipse(500,75,75,50,0,0,Math.PI * 2, false)
        
        // A triangle
        var path4 = new Path2D();
        path4.moveTo(400,225);
        path4.lineTo(450, 150);
        path4.lineTo(500, 225);
        path4.closePath();
        
        
        
        
        
        // Fill the circle in black
        context.fillStyle = '#eee';
        context.stroke(path1);
        context.fill(path1);
        
        // Fill the square in red
        context.fillStyle = 'red';
        context.stroke(path2);
        context.fill(path2);
        
        // Fill the ellipse in green
        context.fillStyle = '#0f0';
        context.stroke(path3);
        context.fill(path3);
        
        // Fill the triangle in blue
        context.fillStyle = 'blue';
        context.stroke(path4);
        context.fill(path4);
    })
</script>