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

Drawing with gradients

From: HTML5: Graphics and Animation with Canvas

Video: Drawing with gradients

Creating gradients using the HTML5 canvas is pretty easy. There is two kinds of gradients: there is linear and there is a radial. The way you create gradients is there are two steps involved. First, you have to create the gradient using the appropriate function to create a gradient of the right type, either linear or radial. Now once you created the gradient, you have to add color stops to the gradient at certain positions in order to create the necessary color transitions. Once you've created the gradient, it can be used anywhere a stroke or a fill style can be used, pretty much like patterns as well.

Drawing with gradients

Creating gradients using the HTML5 canvas is pretty easy. There is two kinds of gradients: there is linear and there is a radial. The way you create gradients is there are two steps involved. First, you have to create the gradient using the appropriate function to create a gradient of the right type, either linear or radial. Now once you created the gradient, you have to add color stops to the gradient at certain positions in order to create the necessary color transitions. Once you've created the gradient, it can be used anywhere a stroke or a fill style can be used, pretty much like patterns as well.

Let's take a look at how gradients work. Linear gradients are defined along a path. There is two points that define a linear gradient. The linear gradient then travels along that path from the first point to the second point. So in this example, we have a gradient defined by the starting point x0, y0, and the ending point, x1, y1. In this case, we've got a light blue color traveling along that line to the lower-right point, x1, y1. Radial gradients work a little bit differently.

Radial gradients are defined by two circles. The radial gradient travels from the edge of the inner circle to the edge of the outer circle. And in this case, we've got the inner circle of a darker blue color, and the gradient travels from the edge of the inner circle to the outer one. To create gradients, you use the createLinearGradient or createRadialGradient functions. The createLinearGradient function takes four arguments, two points. This is the first point. This is the second point, which I showed earlier, and that's the line that the gradient travels along.

The createRadialGradient function takes six arguments, which define the two circles. The first circle is centered at x0, y0 and has a radius of r0. And the second circle is at x1, y1 and has a radius of r1. So that defines the two circles, which define how the radial gradient travels. Regardless of which gradient you create, you use the addColorStop function to add color stops at various positions. The first argument, position, is a floating point number going from 0 all the way up to 1.0. You can kind of think of that as a percentage.

So, for example, a gradient at the 80% position would be at 0.8. You could add multiple color stops at different positions, and you simply define the color using any standard CSS color string to create the color. Let's go see gradients in action. So I'm here in my code. This is the gradients_start file, and this is in chapter 06. And now I'm going to go to my gradients section in my snippets. That's right here. So the first example we are going to do is create a linear gradient.

So let's just copy this example right here, and we'll paste. We've got the call to createLinearGradient right here, and this is the first point. This is the second point. Both of these points start at x of 20 and go from y 20 to 280. This is going to be a straight-line gradient, and then we need to add some color stops. We're going to go from red to blue and then blue to green. So at the 0 position, we're going to start with red and then at the halfway mark, we'll put blue in, and then we'll end up with green at the 100% mark.

Then to display the gradient, we'll simply set the fillStyle of the context to the linear gradient we just created, and then we'll fill the rectangle with the gradient. So let's save, and let's go up and look at the finished result, and you can see that it worked. So in this case, the linear gradient is going from this point here straight down to this point here. Let's see what happens when we change those two points. So back here in the code, I'm going to change this point here to be 220. So now I've got x of 20, 20, and the second point is 220, 280.

So we'll save, and we'll go back to the browser and we'll refresh. You can see now that I've got the gradient going from the top left down to the lower right. So that's pretty good for a linear gradient. Let's try radial. So let's go back to my snippets, and now we're going to copy the code that does the radial one. We'll copy and we'll paste. All right, let's take a look at the code.

So in this case, I'm now creating a radial gradient, and this is the first circle. The first circle has its center point at 525, 150 and has a radius of 20. The second circle is centered at the same location the first circle is but has a larger radius, in this case 100. So we've got two circles that are centered at the same point, but of just different radii. So now we're going to add some color stops to this gradient. We're going to addColorStop and we're going to do the same thing; we're going to red to blue to green. So red goes at 0, blue is at halfway, green is at the 100% position.

We set the fillStyle to be the gradient we just created. And then we're going to just create an arc that has the contents of the arc as the gradient. So after setting the fillStyle, when you call fill, it's going to fill it with gradient. Let's save. Okay, let's go back to the browser and we'll refresh, and you can see that we now have a circle with the radial gradient. So here is the inner circle right here filled with red, and the gradient is traveling from the edge of that circle out to the edge of the larger one. So let's go back to the radial gradient definition and offset the circle a little bit.

So we'll go back to the code, and instead of putting this circle at x of 525 and 150, let's offset a little bit. Let's put this one at y of 100 and we'll put the x, let's say, at 500. And this is going to cause the circle to move up and to the left a little bit. So let's save, back to the browser, refresh, and you can see that the circle was here. Now it's moved up here, and the gradient is a little compressed over this way and a little bit elongated this way.

So we've seen how to create linear and radial gradients, and we've seen how to add color stops and even change the directions and origins of the gradients.

Show transcript

This video is part of

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

37 video lessons · 18361 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.