Tutorials

KodeKite Tools

HTML
Flexbox
SVG
Canvas
More


Canvas Rectangle
Canvas Rectangle

There three functions or methods that draw rectangles on the canvas.


  • fillRect(x,y,width,height)
  • strokeRect(x,y,width,height)
  • clearRect(x,y,width,height)
fillRect(x,y,width,height)

fillRect method is used to draw a filled rectangle.

Syntax

var variableName = canvas.getContext(2d);
variableName.fillRect(x,y,width,height);


Example


strokeRect(x,y,width,height)

strokeRect method is used to draw a rectangular outline.

Syntax

var variableName = canvas.getContext(2d);
variableName.strokeRect(x,y,width,height);


Example


clearRect(x,y,width,height)

strokeRect method is used to clear or erase specified rectangular area, making it fully transparent.

Syntax

var variableName = canvas.getContext(2d);
variableName.clearRect(x,y,width,height);


Example


You can draw any number of rectagnle and also you can clear any area or rectangle.


Practice Task

Open notepad or any other text editor, follow the following points.


  • Use <canvas> element to draw canvas on webpage
  • Assign id <rectangle> to canvas element
  • Give width and height of 200 200 respectivelly
  • Use inline style to style canvas element
  • Give border and to canvas using css styles
  • Border should be 3px solid green
  • Use javascript to draw rectangle on canvas by using fillRect method and clear some area of rectangle using clearRect method

save file with name task.html or task.htm and then open it using any browser and see results.


Solution