Tutorials

KodeKite Tools

HTML
Flexbox
SVG
Canvas
More


Canvas Introduction
Canvas Introduction

The canvas element is an HTML5 element used to render graphics on a webpage.It is used to draw graphics such as graphs, make animations, games, iamges by using javascript. It has width, height, style and id attributes, width and height attributes are used to increase and decrease size of canvas, style attribute used to style cnvas and id attribute is used for accessing canvas.

Syntax

<canvas id="canvas" width="width" height="height" style="CSS styles"></canvas>


You can define one or more than one canvas elements in a document and put alternate content between <canvas> and </canvas> element to display message when there is an error or your browser does not support canvas element.

Rendering Context

Initially <canvas> is a blank element which means it has nothing to display in browser but it uses javascript to render context on webpage. It uses getContext() method to render context and funtions for drawing, function takes one parameter of type context 2d.

Syntax

var variableName = canvas.getContext(2d);


Here 2d means <canvas> is 2-dimensional element with co-ordinates of (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 <MyCanvas> to canvas element
  • Give width and height of 200 200 respectivelly
  • Use inline style to style canvas element
  • Give border and background color properties to canvas using css styles
  • Border should be 5px solid yellow
  • Background color should be green

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


Solution