Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Drawing basic shapes: Rectangles and lines

From: HTML5: Graphics and Animation with Canvas

Video: Drawing basic shapes: Rectangles and lines

In this movie, we were going to see how to draw some basic shapes. Now we've already seen these couple of times in other examples, but let's take a deeper look at how rectangles and lines are drawn. Now, rectangles are the only primitive shapes supported by canvas. Unlike, say another technology like SVG that also supports the ellipse, the canvas only has the rectangle as what is called a primitive shape. It's a shape that's very simple to draw and it only requires one routine. Rectangles are pretty much the only primitive one supported by canvas.

Drawing basic shapes: Rectangles and lines

In this movie, we were going to see how to draw some basic shapes. Now we've already seen these couple of times in other examples, but let's take a deeper look at how rectangles and lines are drawn. Now, rectangles are the only primitive shapes supported by canvas. Unlike, say another technology like SVG that also supports the ellipse, the canvas only has the rectangle as what is called a primitive shape. It's a shape that's very simple to draw and it only requires one routine. Rectangles are pretty much the only primitive one supported by canvas.

There are three functions for operating rectangles. The first one is the clearRect function, which erases the rectangle defined by the parameters you give it. In other words, it makes the area fully transparent; it gets rid of the contents of that rectangle. The other two are strokeRect and fillRect. strokeRect outlines a rectangle with whatever the current stroke style is, and fillRect fills the rectangle with whatever the current fill style is. Now all three of these rectangle-drawing operations take a starting point of the upper-left corner of the rectangle that you want to draw--that's the point where the rectangle will start-- and then a width and a height.

It makes a rectangle as wide as you say and as high as you say. Unlike other drawing systems where you give it all four points, here all you need to do is specify one point and then how high and how wide you want the rectangle to be. Lines are a little bit different. Lines can be created using a variety of settings for how lines join together and how they end. So let's take a quick look at the line operations. The first two functions, moveTo and lineTo, are used to get ready to draw a line.

So the moveTo function moves the imaginary pen to the given point, but it doesn't actually draw anything. Imagine you are picking you are picking the pen up from the paper and moving it to its new location. The lineTo actually does draw a line from whatever the current pen point is to the new point that you give it. The next three properties, lineWidth, lineCap, and lineJoin, determine how the line looks on the screen. So we have already seen the lineWidth before. That determines how wide the line is. The lineCap defines how the ending of line is drawn, and there's three properties.

There is the butt property, which is default, or you can draw lines with round ends or square ends. The lineJoin property determines how lines join together when you do multiple line tos, making the join as a round join, a bevel join, or a miter join, which is the default. The miter limit is related to the miter join, and this the limit at which line joins are cut off and are drawn as bevels. And that defaults to 10, and we'll see that in a moment. The beginPath begins a new set of drawing operations, and the stroke function collects all the current path commands and then draws them.

So we will see how to do that in a moment. But first, let's get started drawing some basic rectangles. So in my snippets, I'm under the Rectangles section, and I am going to open up my file called rectangles_start. And here is where I am going to paste my code in. So I am going to go back to the snippets, and I am going to take the first two sets and I am going to copy that and paste it in. So in this case, we are going to draw first a stroked rectangle, and it has a blue line that is five pixels wide, and then we are going to draw a fill rectangle.

So let's save and go to the browser. Okay, so you can see there is the operations right there. There's the stroked one. There is the filled one. Let's go back to the code. So now I'll copy and paste the other two. Actually, I'll do this one first. I'll copy that. We'll paste it in. In this case, we have a rectangle that's both stroked and filled. So the stroke will be red and the fill will be yellow. Then we have increased the lineWidth to 10. So we've set the new properties, and then we draw.

So we fill and stroked the rect, so let's save and refresh the browser. You can see that now you got three rectangles, different kinds of properties. And then lastly, let's clear a rectangle. So I am going to copy and we'll paste. So here is what we are going to do. We are going to create a rectangle that cuts across all three of the rectangles we drew previously. So you can see that this rectangle starts at the 25, 25 point, near the upper left, and has a width of 100 and a height of 125.

In fact, they all have the same height and width. They just happen to start at different X points so that they move further and further to the right along the canvas. And then the clear rectangle is going to start at the X of 15, so before the first rectangle. And the Y point of 75, and it is going to be 450 pixels wide and 50 pixels high. So let's save this and see what it does. So when we refresh, see all three rectangles got drawn, but then a rectangle right here got cleared out from underneath them.

So that's how you can clear a rectangle. Let's now take a look at the lines. So I am going to go back to my example file. I'm going to open lines_start now. So here is the starting point. Let's go back to the snippets. So now let's go up to the lines section, which is right there, and we've got varying examples that we are going to do. So the first example, we will copy these lines right here. We'll copy and we'll paste. Let's review with these do.

So what we are doing here is creating a for loop that goes from 0 to 10, and we are going to draw lines of varying widths. Now, to draw a line, the way that you do this is you always begin a drawing operation with the beginPath function. That tells the canvas that a path operation, which lines are part of, are about to begin. So then we set that lineWidth. In this case, we are going to set the lineWidth to whatever the loop counter is +1 pixel. So it will start off at 1 and end at 11. And then we are going to move to the X position here and the Y position defined by the current line that we were drawing.

And then we are going to draw a line to the X position of 475 and the same Y. So this will draw 10 lines of varying widths, and after each line is drawn, we call stroke. That actually fills the line in. So the process is called beginPath. Do your line operations. Then call stroke, and that will stroke the lines, so let's do that. We are going to save, and then we are going to go to the browser. You can see in the first example that's what's happened. You started off drawing lines of varying widths, going from 1 up to 11 and from this X to this Y.

Now, let's see how to draw lineCaps. So to draw lineCaps, we are going to go back to snippets and we are going to copy this code over, and we are going to copy these lines. Remember, there's three end caps. I will copy that. So we'll paste it below this one here. So notice that we've got three canvases: we have got canvas1, canvas2, and canvas3. So the canvas1 is going to be the line widths. The next canvas would be done with line caps.

So let's scroll back up. Here's canvas2. So what we are going to do is draw two guidelines so we can clearly see how the line ending caps are different for each operation. So we draw two cyan lines of width 1 at the left and right side of the canvas, and then we are going to draw lines using each one of the lineCaps. So we are going to set our lineWidth to be 25 and the strokeStyle is going to be black. And then we are going to draw one line with the butt style, one with a round style, and one with a square style, from this position to this position.

So we begin the path, we move, we line, we stroke. And then we do it again: beginPath, moveTo, lineTo stroke. That's the operation for drawing a line. So we save. Let's go back to line example and refresh, and you can see right there, there is the cyan guidelines that we drew. There is the first one. There is the second one. And you can see the start and the end point for each line goes from one cyan line to the other. So here is the butt example, here is the round example, and here is the square ending.

You can see how each one of those line caps has a different appearance. And let's finish up using the lineJoins. So now for the third canvas, we are going to copy these lines right here, go back to our lines, and we'll paste it in. So, similarly to the last example, we get the canvas, in this case it is canvas3. We are going to set the lineWidth to 15 and the strokeStyle to black, and then, again, for each one of the lineJoins, we are going to round, bevel, and miter.

So then we begin the path, move, line, and line. So we are going to draw one line up and one line down, and then we stroke it. So we do one for each of those. We save. Back here in browser, we are going to refresh, and you can see that the three line joins have now been drawn. So there is the round line join, there is the bevel line join right there, and there is the miter line join, where the miter line just continue these two lines here up to a point where they both meet. Now the miter limit controls how much of a ratio there is before the miter gets cut off and looks like a bevel.

So it defaults to 10. Let's go back and play with that for a second. Let's set the context's miterLimit to 20, and we'll save and let's refresh that. So no effect on that one. Let's try it again. Let's put it down to say 5, refresh. One more time, let's put it down to 1. And you can see that when I set the miterLimit low enough, suddenly the miter gets cut off and turned into a bevel.

So that's how you use the miterLimit. All right! So in this example we have seen how to draw lines of varying thickness, varying end cap styles and varying join styles.

Show transcript

This video is part of

Image for HTML5: Graphics and Animation with Canvas
HTML5: Graphics and Animation with Canvas

37 video lessons · 18289 viewers

Joe Marini
Author

 
Expand all | Collapse all
  1. 4m 54s
    1. Welcome
      1m 3s
    2. Using the exercise files
      2m 3s
    3. Using the HTML5 Canvas element in the real world
      1m 48s
  2. 10m 31s
    1. Real-world example: CanvasMol
      2m 9s
    2. Real-world example: Raphaël-JavaScript Library
      1m 47s
    3. Real-world example: The Wilderness Downtown
      4m 1s
    4. Real-world example: Sketchpad
      1m 10s
    5. Real-world example: Pirates Love Daisies
      1m 24s
  3. 3m 28s
    1. Installing the tools
      1m 29s
    2. Exploring the Canvas examples used in this course
      1m 59s
  4. 8m 58s
    1. Introducing the Canvas tag
      6m 30s
    2. Understanding the differences between Canvas and SVG
      2m 28s
  5. 5m 36s
    1. Identifying the Canvas element's methods and properties
      1m 40s
    2. Using the Canvas drawing context
      3m 56s
  6. 43m 14s
    1. Setting and using colors and styles
      3m 19s
    2. Drawing basic shapes: Rectangles and lines
      10m 21s
    3. Understanding the Canvas state
      5m 15s
    4. Drawing complex shapes: Arcs and paths
      9m 15s
    5. Drawing complex shapes: Bézier and quadratic curves
      5m 46s
    6. Rendering text
      9m 18s
  7. 32m 35s
    1. Creating shadows
      6m 41s
    2. Drawing with patterns
      7m 20s
    3. Drawing with gradients
      6m 18s
    4. Using clipping paths
      4m 46s
    5. Drawing images and video
      7m 30s
  8. 35m 42s
    1. Transforming objects using the translate tag
      4m 18s
    2. Scaling objects with the scale transformation
      4m 7s
    3. Rotating objects with the rotate transformation
      4m 33s
    4. Applying a custom transformation
      6m 58s
    5. Compositing in Canvas using globalAlpha
      6m 36s
    6. Manipulating raw pixels
      9m 10s
  9. 41m 23s
    1. Building an image slideshow control
      4m 24s
    2. Using smooth transitions in a slideshow
      4m 28s
    3. Creating a basic animation
      5m 42s
    4. Creating animation with double buffering
      13m 13s
    5. Incorporating Canvas into a real page
      13m 36s
  10. 48s
    1. Goodbye
      48s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5: Graphics and Animation with Canvas.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.