JavaScript Canvas

JavaScript Canvas

JavaScript Canvas

The HTML <canvas> element is used to draw graphics on the fly via JavaScript. It can be used for rendering shapes, images, text, and animations dynamically.

Here's a basic overview of how to use the <canvas> element with JavaScript.

1️⃣ Basic Setup: Adding a Canvas Element

First, you need to include the <canvas> element in your HTML. The width and height properties define the size of the canvas:

<canvas id="myCanvas" width="500" height="500"></canvas>

The <canvas> element does not display anything on its own until you use JavaScript to draw on it.

2️⃣ Accessing the Canvas in JavaScript

To interact with the canvas, you need to get a reference to the 2D rendering context. The getContext('2d') method is used for 2D drawing. Here's how you access it:

<canvas id="myCanvas" width="500" height="500"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); // 2D drawing context </script>

The ctx object gives you access to methods and properties for drawing on the canvas.

3️⃣ Drawing Shapes

You can draw various shapes on the canvas, such as lines, rectangles, circles, and paths.

3.1 Drawing a Rectangle

<script> ctx.fillStyle = 'blue'; // Set the color to fill the rectangle ctx.fillRect(50, 50, 200, 100); // x, y, width, height </script>
  • fillRect(x, y, width, height): Draws a filled rectangle.
  • strokeRect(x, y, width, height): Draws a rectangle outline.

3.2 Drawing a Line

<script> ctx.beginPath(); // Start a new path ctx.moveTo(50, 50); // Move to the starting point ctx.lineTo(250, 250); // Draw a line to (250, 250) ctx.stroke(); // Render the path </script>
  • beginPath(): Starts a new path.
  • moveTo(x, y): Moves to a specific point without drawing.
  • lineTo(x, y): Draws a line from the current position to the specified point.
  • stroke(): Renders the path on the canvas.

3.3 Drawing a Circle

<script> ctx.beginPath(); ctx.arc(250, 250, 50, 0, Math.PI * 2); // x, y, radius, startAngle, endAngle ctx.fillStyle = 'green'; ctx.fill(); </script>
  • arc(x, y, radius, startAngle, endAngle): Draws a circle (or arc).
  • fill(): Fills the shape with the current fill style.

3.4 Drawing a Path (Polygon)

<script> ctx.beginPath(); ctx.moveTo(100, 100); ctx.lineTo(200, 100); ctx.lineTo(150, 200); ctx.closePath(); // Close the path ctx.fillStyle = 'red'; ctx.fill(); </script>
  • closePath(): Closes the current path by drawing a straight line back to the start point.

4️⃣ Drawing Text

You can also draw text onto the canvas.

<script> ctx.font = '30px Arial'; // Set the font style and size ctx.fillStyle = 'black'; // Set the text color ctx.fillText('Hello, Canvas!', 100, 100); // Text, x, y </script>
  • font: Sets the font style and size.
  • fillText(text, x, y): Draws filled text.
  • strokeText(text, x, y): Draws text with an outline.

5️⃣ Image Drawing

You can also draw images on the canvas.

<canvas id="myCanvas" width="500" height="500"></canvas> <img id="myImage" src="image.jpg" style="display:none;" /> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); const image = document.getElementById('myImage'); image.onload = function() { ctx.drawImage(image, 50, 50, 100, 100); // x, y, width, height }; </script>
  • drawImage(image, x, y, width, height): Draws an image on the canvas.
  • The The onload event is used to ensure the image is fully loaded before drawing it.

6️⃣ Canvas Animation

You can animate graphics on the canvas by using the requestAnimationFrame() method, which allows you to create smooth animations.

<canvas id="myCanvas" width="500" height="500"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); let x = 0; function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas ctx.fillStyle = 'red'; ctx.fillRect(x, 50, 50, 50); // Draw a red square x += 2; // Move the square if (x > canvas.width) x = 0; // Reset if it goes off the screen requestAnimationFrame(animate); // Request the next frame } animate(); // Start the animation </script>
  • clearRect(x, y, width, height): Clears a rectangle area on the canvas.
  • requestAnimationFrame(): Requests the browser to call the animate() function again before the next repaint.

7️⃣ Canvas Events

You can also handle events on the canvas, such as mouse clicks or touch events, by adding event listeners to the canvas element.

<canvas id="myCanvas" width="500" height="500"></canvas> <script> const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d'); canvas.addEventListener('click', function(event) { const x = event.offsetX; // Get the mouse position relative to the canvas const y = event.offsetY; ctx.fillStyle = 'blue'; ctx.fillRect(x - 25, y - 25, 50, 50); // Draw a square at the clicked position }); </script>
  • offsetX and offsetY: Provide the mouse position relative to the canvas.

8️⃣ Clearing the Canvas

If you want to clear the entire canvas, you can use the clearRect() method:

<script> ctx.clearRect(0, 0, canvas.width, canvas.height); // Clears the entire canvas </script>

Conclusion

The Canvas API in JavaScript is a powerful tool for drawing and animating graphics directly in the browser. Whether you want to draw simple shapes, images, or create complex animations, the <canvas> element combined with JavaScript provides endless possibilities for web development.

Let me know if you want to explore any specific canvas functionalities in more detail! 😄

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close