Tutorials

KodeKite Tools

HTML
Flexbox
SVG
Canvas
More


Canvas Path
Canvas Path

A canvas path is a list of points that is used to define the boundary of vector shapes. Paths are used to draw many types of shapes such as circles, rectangles, polygons, squares etc. Paths have their own predefined methods used to begin path, close path, stroke, fill, move paths.


  • beginPath()
  • closePath()
  • stroke()
  • fill()
  • moveTo(x,y)

Before you start to draw paths on HTML5 canvas, first you have to begin path for it then draw some drawings and then close path.

beginPath()

beginPath() method is used to create a new path, once path is created you can use any drawing command to draw any shape on HTML5 canvas. Each drawing command is directed between begin path and close path methods.

Syntax

var variableName = canvas.getContext(2d);
variableName.beginPath();

closePath()

closePath() method is used to close created path, once path is closed the drawing commands are directed to context.

Syntax

var variableName = canvas.getContext(2d);
variableName.closePath();

Stroke()

stroke() method is used to draw shape by stroking its outline.

Syntax

var variableName = canvas.getContext(2d);
variableName.stroke();

fill()

fill() method is used to draw a solid shape by filling the path's content area with colors.

Syntax

var variableName = canvas.getContext(2d);
variableName.fill();

moveTo(x,y)

moveTo() method is used to change position of paths using co-ordinates (x,y).

Syntax

var variableName = canvas.getContext(2d);
variableName.moveTo(x,y);


Example


You can use canvas element to draw image, text, graphs etc.


Practice Task

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


  • Use <canvas> element to draw canvas on webpage
  • Assign id <Rect> to canvas element
  • Give width and height of 250 250 respectivelly
  • Use inline style to style canvas element
  • Give border and to canvas using css styles
  • Border should be 5px solid orange
  • Use javascript to fill rectangle with color red

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


Solution