How to redraw a rectangle in canvas?

by raven_corwin , in category: Javascript , 5 months ago

How to redraw a rectangle in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 5 months ago

@raven_corwin 

To redraw a rectangle in an HTML canvas, you will need to first clear the canvas and then draw the rectangle again. Here is a step-by-step guide on how to redraw a rectangle in a canvas using JavaScript:

  1. Get a reference to the canvas element in your HTML document:
1
<canvas id="myCanvas" width="200" height="100"></canvas>


  1. Get a reference to the canvas context in your JavaScript code:
1
2
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');


  1. Draw a rectangle on the canvas:
1
2
3
4
5
6
function drawRectangle() {
  ctx.fillStyle = 'blue';
  ctx.fillRect(10, 10, 50, 50); // (x, y, width, height)
}

drawRectangle();


  1. To redraw the rectangle, first clear the canvas and then call the drawRectangle() function again:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function clearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function redrawRectangle() {
  clearCanvas();
  drawRectangle();
}

redrawRectangle();


This code clears the canvas using the clearRect() method and then redraws the rectangle using the drawRectangle() function. You can call the redrawRectangle() function whenever you need to redraw the rectangle on the canvas.