Saturday, January 21, 2023

JavaScript a snippet very explaned

 const canvas = document.createElement("canvas");

const ctx = canvas.getContext("2d");

document.body.appendChild(canvas);

ctx.beginPath();

ctx.moveTo(30,50);

ctx.lineTo(150,100);

ctx.stroke();

What meand the line that light it up: you think why document body and not body document and what is that wemake it up and work? Was the first thing that I banned from my ideas.

And means that, and is returning to the essencial, remember the DOM? So all is about the DOM to find something in the HTML and connect it to the JS, so the DOM document object model, you remember that we went by the document to finds the things we need and use JS to make that fantastic things. So to find we write the document because is based in the DOM but where we can append to the body, you gonna think what is body so went to the HTML and you gonna see that we have tags and the main ones are inside the DOCTYPE and is the <head></head> and in the sequency <body></body> so we are appending this to the tag body, that was easy to understand isn't true? But we only could do that with the Document Object Model so we have to write before document. You probably do that but don't notice that line be the same read that code line:

const pop = document.querySelector("div");

pop.appendChild(canvas);

So you do that and think there is no document in this append? It was already declared and once declared are already in the comand and doesn't need be repeat. So the document was already delcared in the constant pop so doesn't gonna be repeated in the append.

So that declaration 

document.body.appendChild(canvas); 

Replace the code that is the creation of one constant and the append to the constant the child. The need of one and other is that if the object is used once you really doesn't need economize making a constant.

So this to code lines make the same:

const canvas = document.getElementById("canvas");

const ctx = canvas.getContext("2d");

------

const ctx = document.getElementById("canvas").getContext("2d");

This isn't miracle but only we write directly the ctx without create the const canvas, so is a comand with 2 dots, because in the first part we are sayng DOM, in the middle we are saying the object and in the end we are saying the comand that is in the second line of the code above, so you see that one code can have two dots and this isn't the hard to understad is that nobody explain.

Rute Bezerra de Menezes Gondim

No comments:

Post a Comment