2 Mar 2021

HTML/JavaScript Canvas 2D Drawing Tutorial & Example.


html JavaScript Canvas 2D graphic drawing

2D graphic grawing is an easy styff, Only you have to basic knowlwdge of HTML & JavaScript. Calling getContext(2d|webgl|experimental-webgl) method with proper string over CanvasHTMLElement
Returns CanvasRenderingContext2D. This is a context which os used to draw 2d graphic over canvas element.

    CanvasHTMLElement.getContext("2d")
    
returns 2d graphic drawing object. Or aay context in which , 2D graphic will be drawn.

    CanvasHTMLElement.getContext("webgl");
    
Genrally for 3d graphic drawing,

How to Draw 2d Graphic over HTML Canvas Element?

lets follow the steps, To draw 2d primitive shape triangle, rectangle, circle, line & Text over Canvas Element.

Drawing Rectangle on Canvas with JavaScript.

After getting 2D context from Canvas, To draw rectangular shape object is called rect(x,y, width, height) method of 2d context.
x and y are repersenting 2 dimensional cordinations, Which tells from where to start draw rectangle's top-left corner.
These coordinates are provided relative to Canvas top-left corner in Pixel.


width and height are provided to rectangle acctual dimensions.

<canvas id="rect"> </canvas>

<script>
var ctx2d = document.getElementById("rect").getContext("2d");

ctx2d.beginPath();
ctx2d.rect(50,20, 200 ,100);
ctx2d.stroke();

</script>

Rectange Demo

Drawing circle over Canvas.

Drowing Circle Over Canvas with Javascript

To draw Circle, Call Canvas2dRendringCondex.arc(x,y,radius,startAngle, endAngle, false);


x & y is two dimensional coordinate in pixel.
radius - Radius of a circle. center of circle will x and y coordinate.
startAngle - By default starting angle is started from 3 o'clock.
endAngle - Ending angle of an circle's arc.
Math.PI - 180° half of circle ( Semi-circle).
Math.PI*2 - 360° full circle.
Math.PI/2 - 90° one-fourth of a circle. Quadratic circle.

<canvas id="circcan"> </canvas>

<script>
var ctx2d = document.getElementById("circcan").getContext("2d");

ctx2d.beginPath();
ctx2d.fill = "rgb(184, 88,133)";
ctx2d.arc(150,75, 20, 0*Math.PI, 2 * Math.PI, false);
ctx2d.stroke();

</script>

Circle Demo

Reaction:

No comments:

No Comments

COMMENT FROM MESSAGE