Welcome to part one of a two part lesson on how to draw on an HD PML canvas the finished canvas will
look like this and you will be able to draw on this canvas by clicking and dragging with your mouse
and when you press the button it will clear the canvas.
But how do we get here.
Being able to draw on a canvas on the Web site like that is actually a six step process.
Step one is creating the canvas in the first place.
This is the part that we did in the index that each team l file and step two is styling the canvas.
And this is something that we're gonna do as part of this lesson.
For example one of the things that we're gonna do in terms of styling is give our canvas a black background
in order to draw something on the canvas.
We first have to listen for events.
And what do I mean by events.
An example of an event would be like holding down a mouse button or moving the mouse or lifting the
mouse button.
But why is this important.
Well if we want to draw something when the mouse is being clicked and dragged.
We first have to detect if the mouse is being clicked and dragged and that means we have to set up our
Web site to listen and respond to these events.
The next thing we have to do is actually check where the mouse is on the Web site.
And this means checking the coordinates of the mouse the position of the mouse.
It's given by an X and Y coordinate and it's going to be the job of our event listener to report these
coordinates back to us.
The reason we need these coordinates is so that we can use them for drawing something drawing something
with the mouse involves creating a line between all the coordinates that are reported back to us from
the event listener and after we've done all of that.
The final step is clearing the canvas.
We have to set off the canvas afresh so that we can use it to draw a new number on it.
In making new prediction.
So that concludes the high level overview of what we're going to do with our canvas.
Let's head into V.S. code and write some javascript.
At this point you need to have your server running and you should have your website pulled up on local
host and Google Chrome.
The first thing that we're gonna do is we're going to add our JavaScript in a separate file all our
drawing logic for the canvas.
It's gonna go in a file other than this index thought H2 AML file.
So right click here in the Explorer pane and click new file and give this file a name call it drawing
dot J.S. and this dot J.S. is very important.
Make sure you add that extension jazz of course stands for JavaScript as you can imagine.
And this is also a worthwhile extension to know because these days I'm getting a lot of spam emails
that include malicious javascript code with this J.S. extension.
I remember when I used to have to just watch out for dot e x e files the windows executable is.
But these days I'm getting a lot of spam with this.
J.S. now inside this file let's create a new javascript function so we're going to use the function
snippet here.
This is the second one down and we're gonna give this function a name and this code is going to helpfully
insert a lot of these syntax for us here.
So let's give this function name and let's call it prepare a canvas with the camel casing and we're
gonna delete the input parameters here.
This is not going to take any inputs but inside we're going to log a message we want something to tell
us that this function has been successfully executed in the Chrome developer console.
So I want to type log and insert the log snippet here and I'll just have a very simple log message reading
preparing canvas.
Now I've created a function here in a separate file this drawing that J as file.
How would I call this function from the index.
Thought each html file.
This is a different file after all.
In order to make use of the code that's in this drawing not just file a sum I have to link these two
files and the place I'm going to do that is in the head of the index that HD AML file and the place
we're gonna do that is just below this to do right here.
This is where we're gonna add that script tag just like we've done above and we're going to set the
source equal to our drawing daunt J.S. file.
In this case so the source is our drawing not just file which is in the same folder as our index Dot.
Each time l file and when I close the script tag then I should see the closing tag being inserted here
automatically by V.S. code.
So the script tag is really really handy.
Not only can we point to a file here in our explorer pane but we can also point to a U.R.L. that contains
javascript like with our tensor flow J.S. and of course we can add javascript directly between these
two script tags but now that we've linked to our javascript dot J.S. file with this line of code right
here we can actually call that prepare canvas function right below in our index that each time our file.
So if I write prepare a canvas right here and then just double check that the spelling here matches
the name of the function that is right here and I save my changes on both of these files then I can
go into Google Chrome refresh and then if I bring up the developer console on the right then I can see
that log message preparing canvas right here.
Great.
So now that we've got that working let's style our canvas and we're gonna use javascript to do this.
So in our drawing dot J.S. JavaScript file let's create a constant and let's call that constant canvas
and we're gonna set that content equal to the canvas from the index thought each time l file.
So how can we get hold of this element right here from the index that each time l file inside the drawing
dot J.S. file well we can get hold of it via document dot get element by I.D. We're gonna supply the
I.D. of the canvas element which is my canvas hyphenated to this get element by idea function and that
will get hold of the canvas for us.
Now of course you can get hold of any element by its idea he doesn't have to be the canvas.
You just have to supply the idea of that element between the parentheses right here.
Now the reason we're getting hold of the canvas here is because we're actually interested in manipulating
this canvas.
We're gonna style it right and the way we're gonna be able to do that is by has something called the
canvases context.
Now I know that's a very strange word but every time we want to do something to this canvas like drawing
it or change its colour we have to go through something called the context.
In other words the context is an object that provides methods and properties for drawing on the canvas
or manipulating the canvas.
So I want to store this context in a variable called context so const context is equal to and then when
I get hold of the context through the canvas with canvas don't get context and in the parentheses I'll
supply to D as you can see from the quick documentation.
There are two dimensional and three dimensional canvases.
We're gonna be using a two dimensional canvas now to see the context in action.
Now that we've got it as an example let's make our context white and we can do that with context dot
Phil style and context dot Phil style is a property of the context and we can set the Phil style here
with a hex code for a colour and hex code for white is the pound symbol and then six trailing Fs.
Now that we've decided on the Phil style let's draw a white rectangle on to our canvas so we can create
that white rectangle with context dot Phil rect and this is a method.
So we're gonna have these parentheses I'm going apply for inputs and X and Y.
So this is the positioning of the rectangle.
And if we want that to be at the origin it'll be 0 0 and then we have to decide on the sizing of this
rectangle a width and a height.
And if we want the entire canvas to be filled we can do that with client width so canvas top client
width.
And for the entire height you guessed it it's canvas dot client height.
So I'll add that semicolon at the end save my changes and then refresh my page and what I see is a white
canvas.
So that's the context and action.
It allows us to manipulate the canvas.
But let's make this canvas black instead.
So instead of providing the hex code for the colour here what we can do is we can go to the very top
of our drawing that jazz and critic constant him for the background colour.
So quite like having a lot of the constants with these values at the top of my files second access them
really really easily the hex code for black by the way is a pound symbol and then six zeros.
So this is a black colour and then I can use that constant down here instead of setting the Phil style
to White I want to set it to background colour if I save and refresh.
We should see that canvas in black on our website.
Brilliant.
So that pretty much completes most of the styling that we're going to do for the canvas.
Now it's time for the third step and that's adding a listener and the listener is there to be able to
detect clicking and dragging.
Let's add the very first listener to our website and we can do that by grabbing hold of our documents.
So this is our entire site and adding an event listener to it.
So the event listener has already suggested by yes code and all they need do is type 80 and press enter
and in the parentheses I have to supply a number of things.
The first is the name of the event that I want to listen to.
So I don't want to listen to something called Mouse down so that's when the mouse is being clicked and
then I have to provide another input to this add event listener method and that's what should happen
when the mouse is pressed.
So this isn't like a single value like a number or a string.
Instead I've got to add some code here and I add a function and this function is not going to have a
name and it's going to have a single parameter namely our event.
So this is what our code looks like for the event listener.
We've got a name of the event and we've got a function as the second input.
Now I know the syntax here looks a little bit intimidating and we have to remember to add the semicolon
here at the end but the purpose of it is actually very simple.
Essentially when this event is detected the mouse gets pressed then all the code between these two curly
braces gets executed.
Let's try this out.
Let's add a log statement here and we're just gonna add a log here that reads click.
Exclamation mark.
And if I save my changes head back into chrome refresh then if I take my house and just click somewhere
then you can see the console log appear here.
So if I click multiple times then you get this whole thing being executed a total of nine times.
Right.
So the functionality of this bit of code is a lot less complicated than what the syntax lets you believe.
We add a listener to our document that detects if the mouse is being pressed down and when the mouse
click is being detected then this is the code that gets executed.
What if we get notified of the event now.
If we hover over this add event listener but we get to see the quick documentation and we get to see
the technical jargon for what it is that we've done so we've appended an event listener and this function
here.
The second argument is a callback and the callback will be invoked when the event is dispatched.
So there you go.
That's the technical explanation for what this code does.
Now of course mouse down isn't the only event out there so which other events can we listen to.
Well if we head over to the NBN web documentation on this topic then we get this event reference page
and here we've got events grouped by category.
So what I'd like you to do as a challenge is I'd like you to log the word move every time the mouse
moves on our website.
And I recommend you to use this page right here.
This documentation to help you write the code.
I'll give you a few seconds to pause the video before I show you the solution.
Ready.
Here's how it works.
So if we scroll down a little bit here on this page we can see that under mouse events we have this
event here called mouse move and this is the event that we're gonna add a listener for on our document.
So heading back into as code I can even copy this whole thing pasted below.
Change the name of the event from mouse down to mouse move and then just change by log message to move
and that's it.
So let's take a look at what this looks like on our Web site.
Saving the changes and heading back into chrome and refreshing the page you can see that this event
gets triggered loads and loads of times even for very small movements of the mouse.
Great.
Now that we've got our listener working let's take it to the next level and grab our mouse coordinates.
How we're gonna do that.
Well we can actually get them from the event here in our callback.
In other words this function here doesn't just execute all the code between these two curly braces when
the event is triggered but it also gives us a handle on the event that triggered it in the first place.
And it's this event that will have the mouse coordinates inside of it.
Let me show you how to get a hold of them.
I'm going to modify my log message here and I'm going to have that log message read x coordinate and
then just outside of the string I'm going to add that plus operator and then I'm going to use that event
that I've got from my callback and I'm going to use the client X prop..
So this is the x coordinate of the mouse when the mouse gets clicked and then the y coordinate.
As you can guess is simply event dot client y.
So let's see what these coordinates all by saving the changes heading back into chrome refreshing.
And then if I click somewhere I can see that right here is coordinate 8 0 8 and 2 6 7.
Now I've got a challenge for you again.
Can you find the part of the Web site where the coordinates are 0 and 0 0 for x and 0 for y.
Can you find the origin of the document.
I'll give you a few seconds to pause the video before I show you the solution so I'm guessing you did
a bit of clicking around and at this point you might have discovered that the origin is in the top left
corner.
This is where both X and Y are gonna be equal to zero.
So the reason for it.
Just double checking this is because it gives us an understanding of how this coordinate system actually
works.
So if the top left corner is at 0 0 then what we've learned is that along the x axis.
So going horizontally to the right we get an increase in the x values and on the vertical axis going
down we get an increase in the y values.
But why do we care about these coordinates in the first place.
The answer is is that we need these coordinates for drawing the way our drawing will work is it will
draw a line between two points and the way we know where those points are on our canvas is through the
coordinates of these points.
So point one might be at X is equal to ten and y is equal to fifteen and point two might be at X is
equal to fifty two and y is equal to twenty.
So what this means is that what we're actually interested in in order to draw that line are four different
values the X and the y coordinate of where the mouse was initially and then the x and y coordinate of
where the mouse has moved to or where it is currently.
So the previous x and the previous y will be the past values and the current X and current Y are the
current location of the mouse.
And of course the way we get these points is by tracking where the mouse is moving to.
Now given that we're interested in these four values let's go back into the US code and create four
variables to store these coordinates.
So I want to come back up here and I'm going create four variables.
The first one will be called Current X. And it's gonna get an initial value of zero.
The second one will be called current Y.
And again they'll have a value of zero initially and for the past values I'll see previous x is equal
to zero and far previous Y is equal to zero so now that we've got our initial values or we've got our
variables that are gonna be holding onto them we can have a think about how to update these variables
as the mouse moves.
We're going to update these values in our file.
Well we're going to do that inside the callback inside this function right here when our mouse move
event is triggered.
So when it delete this line right here and the first thing I'm going to do is I'm going to set the previous
value of x equal to the new value of X..
Right.
The current value of x and then I'll take the current value of x and update it with the actual position
of the mouse.
So event dot client x.
So this way the current value of x is always updated to where the mouse is currently.
And we're just always storing where the mouse was the previous time when this was executed in line 23.
We're just going to set the previous value of x to what this value was the last time when this function
was called.
Now let's do the same thing for our y values.
So previous Y is equal to current Y and current Y is equal to event dot client why now.
Just before I save and refresh my website let's log the current x value just to see what it looks like
in our console.
And this is also a chance to kind of learn a little bit about string interpolation in JavaScript.
We've already learned about this with Python f strings and we've come across those in the previous modules
so JavaScript has something very very similar.
And instead of using these single quotes what I'm actually gonna do is I want to use the tactic and
the tactic allows me to write something like current x and then inside of this closing back to care
I want to put a dollar sign some curly braces and then provide the current X so I can actually use my
javascript variable name here.
Current X inside of these curly braces and this dollar sign.
And what this allows me to do is not use the plus operator that I've got up here and this makes the
syntax really really readable.
So it's quite nice.
Just make sure you use the back ticket instead of the single quote.
All right.
So let me save and head back into chrome refresh and then I'll move my mouse and you can see the x value
updating as I move my mouse around.
But we don't actually want to draw on the entire Web site.
Right.
We just want to draw on our canvas.
And what this means is that we should actually shift the origin from the top left corner of the page
to the top left corner of our canvas.
And in order to do that we need to calculate the offset from the top and the offset from the left with
these two values in hand.
We can adjust our current X and our current Y.
So let's head interviews code and make those adjustments.
The way to get hold of the offset is again through the canvas and the canvas has a property called offset
left for the x value by subtracting the left offset from our mouse position.
We're halfway there to moving our origin to the top left corner of the canvas for our y.
Again we're going to use canvas thought and this case we're gonna go with offset top and this will complete
moving our origin.
So I'll save a comeback into our site refresh and then what you see is that if I go and position my
mouse at this corner we've got the origin here at 0 0.
Fantastic.
This lines is up for the next step namely actually drawing our lines.
So how does one actually draw something on a canvas.
Well if you go to the developer documentation on MGM and check out the canvas tutorial you can read
a very very in-depth tutorial on how to draw on a canvas.
But what it actually comes down to for us are five steps.
The first thing that we need to do is actually create something called a path and we can do that with
a method called begin path what's a path a path is actually just a list of our coordinates.
It's not the actual line it's just the list of the coordinates.
So that's the one creating a path.
Then what we have to do is we have to move the starting point of this path to where a mouse is at.
So this is something we can do with the move to function.
This will set the starting point for our line and that's going to be step three line to the line to
method will actually create a line for us.
It won't draw it it will still be invisible but it will actually create a line between the starting
point in the path and the ending point in the path.
It's essentially just going to connect these coordinates.
The next step is closing the path because we're pretty much done with it now.
So we can close it.
And the final step is actually drawing the line and we accomplish this with a method called stroke stroke.
We'll actually draw the line onto the screen for a detailed explanation of all of these methods and
many more.
You can actually head over to W three schools and go to the canvas reference and what you see there
are all the methods I just mentioned explained in detail.
So this is where you can go for the documentation.
Now let's head into this code and actually draw our line.
I'm going to get rid this log statement right here and I'm going to do these five things I'm going to
begin the path move to line to close path and stroke and the object that's going to help us is going
to be our context our context is going to be what will allow us to call this begin path method.
So begin path will create our list of coordinates then context dot move to will set the starting point
of the path.
So where we should begin the line and the starting point will be given by well our previous ex and our
previous why.
So these coordinates will mark at the starting point of the line that we're going to draw the ending
point of the line is gonna be where we're gonna draw the line to.
So with context dot line two we can provide the ending point and that'll be of course the current X
and the current Y.
Now we can close the path and finally we can draw our line and that's with context dot stroke and that's
it.
So let's save this code head back into chrome refresh and then let's mouse over our canvas see anything.
I don't see anything actually.
But why not.
Well well actually drawing a black line at the moment and black on black unfortunately is invisible.
So we're gonna have to style that line.
Let's change the line color to white coming back into V.S. code.
I'm going to create a constant at the top that reads line underscore color and that is equal to white.
By providing that hex code and then just below styling the canvas I'm going to style it a little further
by setting these stroke style so context dot stroke style will allow me to set the color of the line
so stroke style with a capital S for style is equal to and then I'm gonna set it equal to white.
That line color I set earlier.
Saving it and coming into chrome and refreshing will now allow me to see what I'm drawing onto my canvas
um this is I guess a piece of abstract art but what I can do to improve my trying here is to make my
line a little thicker because this is a very very thin line on a very large canvas.
So let's add a constant at the top again for the line width.
So um when I call it line width in all caps and I want it to be equal to I think 15 would be a good
thickness for the line actually.
So now I can come down here and change the width of my line but I think this is actually a good point
to ask you to have a go at doing this yourself.
Try and Google for the M.D. and documentation to change the line width and give this a go set the line
with equal to 15.
Pause the video I'll give you a few seconds before I show you the solution.
Ready.
Here's the solution.
If you check the documentation for the canvas then what you'll find is there is actually a property
called line width.
So here under line styles even on W3 schools you can see what the name of the property is.
So we can use it to set overturn the current line width.
We're interested in setting it to 15 and we're gonna do that again through the context with line width
and we're to set it equal to our constant from above line with like so if I save the changes or refresh
then I can see what a thicker line looks like but upon inspection it does look a little strange right.
Why is it looking so jagged.
The reason is is that we haven't connected all the lines here that we're drawing.
Every time the mouse moves we haven't specified how to join the lines.
So let's do that in this code here where we're styling our canvas.
There is actually a property called line join that we can set and line join can take a number of different
values.
But the one that will look best is called round.
If you check the documentation here and look at what line joint actually is.
Then you get this little example here and you can click on tried yourself to play with the example.
And if I zoom in a little bit here to make this a lot more clear then I can join this property here
from round two.
See Bevel and run the example and you can see this little corner here where there joining the lines
change.
So here's miter and you could see that it's pointy with bevel.
It gets cut off and with round there's a round joining segment that gets added here.
So what this means in the context of our Web site is by saving and refreshing here is we get a nice
smooth line that we're drawing.
Brilliant.
So this concludes part 1 of drawing on a canvas and we've covered quite a few different topics here
actually.
So this was been a very very in-depth lesson and we've learned everything from how to create your own
JavaScript files and add them to your project and link them to the index thought html file.
And we've also learned how to get hold of particular elements in your HMO file and manipulate and use
them in a javascript file then we've learned about how event listeners work and how the coordinate system
works on a Web site.
And finally we've learned how to draw on an HDMI five canvas in the next lesson.
We're gonna be fleshing out this drawing logic a bit more so that we will be able to draw on our canvas
when we click and drag rather than just mouse over it for all of that and more.
I'll see you on the next lesson.