JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How do I draw graphics with the Canvas API?

Asked on Aug 21, 2024

Answer

The Canvas API allows you to draw graphics using JavaScript by providing a drawing context on a HTML canvas element. Here's a simple example to get you started with drawing a rectangle.
<!-- BEGIN COPY / PASTE -->
        <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
        <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = 'blue';
            ctx.fillRect(20, 20, 150, 75);
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "canvas" element is defined with a specific width and height.
  • The "getContext('2d')" method is used to get the drawing context, which provides methods and properties for drawing.
  • "fillStyle" sets the color used for filling rectangles.
  • "fillRect(x, y, width, height)" draws a filled rectangle on the canvas.
✅ Answered with JavaScript best practices.
← Back to All Questions