Captivating Canvas (Part 1)
🌟CAPTIVATING CANVAS 🌟
PART - 1
Objectives:
After reading and writing the codes on your own, you will be able to:
- Render 2D graphics on your webpage.
- Draw paths and rectangles using <canvas> element.
Pre-Requisite:
- Basic knowledge of HTML.
- CSS
- Basic Javascript.
- DOM manipulation (DOM and BOM webAPIs)
LET'S START CODING
height
and width
property. In order to draw graphics on the canvas we use a JavaScript
context object, which creates graphics spontaneously when needed.
<canvas> element :
The above codes show the markup needed for using a canvas.
In line 26 : There is some text, and we haven't mentioned
height and width. So default values are 300 pixels × 150 pixels (width × height).
In line 27 : Here also there is a text but there height and
width of canvas is mentioned.
In line 28 : This time I have put a image inside the canvas
using <img> tag.
(The id attribute isn't specific to the <canvas> element but
is one of the global HTML attributes which can be applied to any HTML
element (like class for instance). It is always a good idea to supply an
id because this makes it much easier to identify it in a script.)
But, what will be it's output?? What do you think?
It is actually a blank webpage.
Now here let me make some points clear:
-
What ever written between <canvas> and </canvas>
will never be displayed on an browser's webpage that supports canvas.
So what ever scripting, markup or styling we apply the text given and <img> inserted in line 27, 28 will not be displayed. But it is also important to add text or other media (called fallback content). Lets see why? - Browser by default will ignore the fallback content inside canvas element. But screen readers, spiders and other automated bots can access that fallback content. Providing useful fallback text or sub DOM adds accessibility to an otherwise non-accessible element.
-
But we can apply CSS to the canvas element like any other
HTML elements.
Lets apply some CSS. NOW the web page will look like this 👇
Rendering Context (script part) :
The canvas is initially blank. To display something, a script first needs to access the rendering context and draw on it. The <canvas> element has a method called getContext(), used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify "2d" to get a CanvasRenderingContext2D.Some-tips:
- The script includes a function called draw(), which is executed once the page finishes loading; this is done by listening for the load event on the document. This function, or one like it, could also be called using setTimeout(), setInterval(), or any other event handler, as long as the page has been loaded first.
- if (canvas.getContext) => is used to check whether the browser is supporting the canvas.
function draw() { const canvas = document.getElementById("tutorial"); if (canvas.getContext) { const ctx = canvas.getContext("2d"); } } draw();If I continue like this, many would get bored. Lets checkout some examples to keep up the interest.
Example 1:
Drawing Shapes with Canvas :
Now that we know how to render the canvas, lets see how to draw
rectangles, triangles, lines, arcs and curves, providing familiarity with
some of the basic shapes. Working with paths is essential when drawing
objects onto the canvas and we will see how that can be done.
The GRID
The canvas as well as the the standard viewport follows a coordinate
system.
Normally 1 unit in the grid corresponds to 1 pixel on the canvas. The origin
of this grid is positioned in the top left corner at coordinate (0,0). All
elements are placed relative to this origin. So the position of the top left
corner of the blue square becomes x pixels from the left and y pixels from
the top, at coordinate (x,y). Later we will see how to scale, translate and
rotate the grid.
Drawing Rectangle
<canvas> supports two primitive shapes - Rectangle and Path. Other
shapes can be derived from these two shapes.
First let's look at the rectangle. There are three functions that draw
rectangles on the canvas:
Drawing Paths
A path is a list of points, connected by segments of lines that can be of different shapes, curved or not, of different width and of different color. A path, or even a subpath, can be closed. To make shapes using paths, we take some extra steps:- First, you create the path.
- Then you use drawing commands to draw into the path.
- Once the path has been created, you can stroke or fill the path to render it.
-
beginPath()
=> Creates a new path. Once created, future drawing commands are directed into the path and used to build the path up. - Path methods : Methods to set different paths for objects.
-
closePath()
=> Adds a straight line to the path, going to the start of the current sub-path. -
stroke()
=> Draws the shape by stroking its outline. -
fill()
=> Draws a solid shape by filling the path's content area.
Now lets see how these can be used.
Example 2:
CODE 👇: STYLE
body{ margin: 1.5rem; padding: 1.5rem; border: 2px solid red; display: flex; justify-content: center; align-items: center; } canvas{ /* See the difference of two types of shadows */ box-shadow: 0px 0px 20px red; filter: drop-shadow(0px 0px 5px blue); }HTML
<canvas width="400" height="400"></canvas>SCRIPT
function draw(){ const canvas = document.querySelector("canvas"); if (canvas.getContext) { ctx = canvas.getContext("2d"); // Set line width ctx.lineWidth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // CLearing Door Entrance ctx.clearRect(140, 200, 20, 60); // Roof ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath(); ctx.stroke(); } } draw();
Lets wrap up, this blog here.
You may think, what so special about
this canvas, its looking like complex drawing tool like "Turtle in
Python". But its not that. Let me show you how amazing websites you can
create, once you cover up all the basics of 2D and 3D rendering. Check
these 👇.
Comments
Post a Comment