Sign In | Subscribe

Enter your Sign on user name and password.

Forgot password?
  • Follow us on:
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of HTML
  • Discussion

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Lecture Comments (4)

0 answers

Post by Eric Rapinchuk on May 10, 2012

add this at the top for the pic...

var img = new Image();
img.src = ("nightpan.jpg");

0 answers

Post by Eric Rapinchuk on May 10, 2012

This code works guys... ;)

<!DOCTYPE html>
<link rel="stylesheet" href="css.css"></link>
<body onload="draw()"> <!-- I NEED THIS -->

<h1>Canvas Element</h1>
<p>This isn't an image, it's a canvas.</p>

<canvas id="draw" width="200" height="200">
Sorry, your browser doesn't support the canvas element :(
<script type = "application/javascript">

function draw() { <!-- i needed this?!!?!?!? -->
var paint = document.getElementById("draw");
var ctx = paint.getContext("2d");

ctx.fillStyle = "rgb(200,0,0)";
ctx.fillRect (10, 10, 55, 50);

ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (20, 20, 55, 50);

ctx.fillStyle = "rgba(0,200,0, 0.5)";
ctx.fillRect (30, 30, 55, 50);

ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
ctx.fillRect (40, 40, 55, 50);

ctx.fillStyle = "rgba(200,0,200, 0.5)";
ctx.fillRect (50, 50, 55, 50);

ctx.fillStyle = "rgba(0, 200, 200, 0.5)";
ctx.fillRect (60, 60, 55, 50);

<!-- i took the if/else statement out :(-->


0 answers

Post by Richard C. Witt, Jr. on December 13, 2011

I've been able to replicate all the code example except this one. Did you have a CSS style sheet that was being referenced too? The only thing that appeared in my Browser was this:
Canvas Element

This isn't an image, it's a canvas

Nothing other than that appeared. I checked my code to make sure it was what you showed and I tried it in Firefox, Opera. Please advise.

Richard C. Witt

0 answers

Post by Alisher Ulugbekov on January 23, 2011

Very instructive. Thanks Brenton.

The Canvas Element

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Creating the Element 0:38
    • What is the Canvas Element?
    • HTML and Canvas Element
    • Example: Canvas Element
  • Creating the Canvas in JavaScript 5:13
    • getContext() Method
    • Checking Browser Support with the getContext() Method
    • Example: Creating the Canvas in JavaScript
  • Drawing in the Canvas 10:13
    • Methods for Drawing in the Canvas
    • 2d Context
    • Example: Creating Drawing in the Canvas
    • Example: Adding an Image and Texts
    • Example: Advance Canvas Element

Transcription: The Canvas Element

Welcome to

This lesson is going to be an introduction and an overview of the canvas element.0002

The canvas element is going to require some knowledge of JavaScript.0009

But you should be learning JavaScript anyway, if you are getting into HTML,0014

because that is where websites really get interesting--where you are doing interactive stuff.0017

I am going to be using a little bit of JavaScript in this lesson, but not too much.0022

This will just be sort of an overview to whet your appetite for getting into JavaScript, and getting into using the canvas element.0026

If you already know some JavaScript, then you can take this a lot further.0034

The canvas element (before I get into how to create it) is a new element in HTML5 that is sort of like an image, a video, or an audio tag,0041

except it is not a type of media that is pre-existing; it is one that is going to be edited on the fly, or created on the fly.0053

So, what it is: it is sort of like a canvas, like a painter would paint on.0063

And then, you, as the web developer, have the paintbrush; and you can paint into this canvas whatever you want,0067

using JavaScript: circles and things like this--and it is very versatile, because you can basically make anything.0073

And you can make it display different information, based on dynamically updating information,0081

based on user input, based on stocks, based on almost anything.0088

So, you can do almost anything with this.0093

In some ways, it is very much like Flash, except it doesn't require a Flash plug-in.0095

It will be supported in every browser that supports canvas; and it is already supported very well in a lot of good browsers today.0101

The first thing you need to learn how to do is create the HTML side of the canvas element.0109

The HTML part is just the canvas tag, very simply: <canvas>, and then </canvas>.0118

And that is basically it; the rest is just giving it little hooks and things, and taking into account backwards compatibility.0124

You will need to give it an ID; I have given it the ID of myCanvas here0134

(and that will allow you to grab it with JavaScript later), and then a width and a height, because there is not a default...0139

I think the default may be 150x300; but you can make it whatever you want.0145

And then, anything in the content of the canvas element is the fallback material.0152

So, if your browser doesn't support canvas, anything that goes in in here (and it can be any sort of flow content) will be displayed to the browser.0156

And so, you don't want to be giving it something that says, "Your browser can't do this; it's horrible."0167

You want to be giving it some alternative content, if possible.0172

So, say you are using canvas to do some stock update graph charts, or something like that.0175

You may just give a static image of a stock chart.0180

Or you can also give a very polite link to a place where they could upgrade their browser to something that will support the canvas element.0185

But you want it to be as useful as possible, and you want to give options.0198

Let's go over code really quickly, and I will create a canvas element.0204

This page here is just a basic page right now; it doesn't have anything in it.0210

But I am going to type the canvas element in--its case-sensitive ID.0217

And you don't need to specify units (in pixels or whatever).0236

Here is the canvas element--very simple.0247

And in its content, I am just going to put a little note...0249

OK, and if I were making an actual website, I would do something a little bit nicer than this--maybe find some fallback content.0265

And I have already prepared some CSS that gives the canvas some styling; I have given it a little border.0273

Now, when I load it in the page and reload (that was what you just saw--what I had prepared earlier), this is what is in the page now.0282

You get the canvas element; and it is 150x150, like I specified there.0292

And the CSS is giving it a little border; and that is it.0297

It is not an image; it is a canvas.0301

That is the HTML side of it--very simple; where it gets complicated is JavaScript.0305

JavaScript--before you can even get started with it, you need to create a reference to the canvas context in JavaScript.0316

Here, I have, in this sort of purple color, some variable names.0325

And you use the getContext method, and there are a lot of different contexts available.0330

In this case, I am getting the 2D context.0335

So, this grabs the myCanvas element, using the ID, and then applies this method to it and gets a context.0339

And that creates a context; and then, you can use that context to access the canvas in the HTML.0348

Another thing you can do with the getContext method is check for browser support of the canvas element.0360

In the last slide, we showed how to get fallback content in the HTML;0367

but you can also use JavaScript to make sure that the browser understands what to do with the canvas element.0371

This is basically the same thing as up here; you have myCanvas.getContext, the same as up here.0381

And of course, myCanvas is a variable that refers to the actual canvas element, which is what this JavaScript is doing.0388

And this check right here: if, if your element that is the canvas element...0398

and then, you put this method on it; and if that works, it is going to evaluate as true.0405

If your browser doesn't know what to do with it--if your browser doesn't support the canvas element,0411

it is not going to know what to do with this method, and it is going to evaluate as false.0418

So, if it is true--if all of this evaluates as true--then you can create your canvas variable right here, myCanvas.getContext("2d").0423

And the 2d context is the context that we are using; but you can use different ones.0432

And then, that puts all of that into this variable.0437

And so, this variable right here, for the rest of your JavaScript session, will now be able to be used as a way of interacting with the actual HTML canvas.0440

A way of doing that: let's copy this code I have prepared--I am going to put it in this script element down here at the bottom (paste it).0456

And I am putting it in the bottom, not in the head, because this needs to refer to the canvas element here.0466

You see, it has this document.getElementByID('myCanvas'); and this myCanvas right here is looking through the ID's and finding this.0477

If you put the JavaScript in the head, the JavaScript will load before the HTML does.0486

And when it gets to this line, it is not going to find it, because it will not have loaded the HTML yet.0491

So, I am putting it after the HTML, just because it is a simple way of doing it.0498

Probably the best way to do it would be to put this script up in the head,0504

and then have an on-load event that waits until the document is finished loading before it executes this JavaScript.0507

But for the sake of this example, it is just simpler and cleaner to put it down here.0513

If I was making an actual website that I was going to put on the Internet, I would do this a little bit more elegantly.0517

This goes after, and so this variable canvas grabs this entire element.0524

And then, this check says, "this element.getContext--if that works, if the browser knows what to do with that,0533

then it is going to create this other variable, canvas.getContext."0540

And this is actually a mistake; this should be something like thecanvas, because you don't want two variable names that are the same (canvas and canvas).0546

That is corrected version there.0561

And then, if it doesn't work, it will throw an error; this is probably the worst way that you could throw an error--0565

giving an annoying alert that just says, "You don't support canvas," without actually giving any backup way of dealing with it.0571

But again, for this example, this is what I am going to do.0579

This is what is going to happen if this fails; it will throw this else.0584

That is the canvas element created in JavaScript now.0589

I refresh, and nothing changed, because all we did is create the JavaScript canvas element there,0597

and pulled up the actual context, which is the 2d context.0605

Now, to draw on the canvas, you need to be using a context.0615

We have already starting using the 2d context; the 2d context is defined at this URL.0620

I think it is in development right now, so that is why it is dev.0627

Eventually, it will be out of development, and then it will be a different URL, although this URL should be able to point you,0630

at that point, to the newer and more complete version of the context.0636

What a context does is: it defines ways to do different things.0641

In the 2d context (there is a 3d context--there are a lot of different contexts; there are browser-specific contexts)...0646

And anybody can make a context, and it can be extended out to whatever the future has to offer.0651

But looking right now at the 2d context, it defines ways to draw various types of shapes, various lines and curves, combining curves0659

and filling them in...segments of shapes, fragments of shapes...0669

You can add images--entire pre-ready images.0674

You can add text; you can control the colors of all of these different elements.0679

You can control the transparency; you can change the location; you can scale them, twist them, turn them, resize them, and things like that.0682

All of that is defined by this context that we are loading in.0693

And once you have loaded it in, then you can get started on actually creating your drawing.0697

Let's do that right in here: we are putting it in the part where, if it evaluates as being able to use it, it creates the canvas.0709

And the first thing we will do is draw a rectangle and paste in some code.0724

What this code here does is draws a rectangle.0731

canvas grabs the entire canvas context that you have created in JavaScript.0738

And fillStyle will just describe the color, basically, because we are going to create a square rectangle that is filled.0744

The fillStyle--this gives you the color: this is red, green, blue--you can think of it as hex, so this is red; this is green; this is blue.0753

This will just be red; it has 200.0760

And then, this is actually drawing into the canvas.0762

These parameters here give you the location and the size.0770

This is, I think, left top; so how many pixels from the left? how many pixels from the top?0774

The rectangle is going to start, and then this is the width and the height.0781

I am saving this, and so now, when I refresh this, there will be a little red square; I have to save first, and there it is.0786

You can see, it is ten pixels from the left, ten pixels from the top; and then, its size is 55x50, as specified right here.0799

And you can also do a little more: for example, you can add transparency.0807

Let's copy this code and create another one just like it.0823

But let's make this one, not red, but--let's make it this color; 200...0829

But then, let's add another little parameter here of 0.5; and this last one is going to be the transparency.0837

This will show up as 50% transparent.0848

And now, I am going to move it down; the size is 150 right now, so let's move it down to, say, 45x45.0853

Save; oops, it is still red--I made a mistake here.0868

This needs to be rgba for alpha transparency; there.0889

So now, you can see that the blue one is 50% transparent, and it overlaps here.0898

So, if I didn't have this a in here, and I didn't have this, then it would just be blue, and it wouldn't be transparent, and you couldn't see through it.0904

So, this shows the power of a canvas element.0914

All right, the last thing I am going to go through is: I am just going to show some other things you can do here.0922

Say you want to add an image--this image: newyork.jpg.0939

I will actually load it for you, so you can see it if you want.0949

It is just a long panoramic image of New York; OK.0955

First, you need to define the image right here, and then this method right here, drawImage.0963

And then, you put the name of the image (which is this variable right here), and then the position.0975

And I think I have this set up wrong; I am going to copy from over here instead--I want this code, because you need to define the image first.0980

You create the image element first; and then you set the source to the URL.0996

And I'll make it 00, so it fills the whole screen.1005

Go over to the browser; and it loads the image in the canvas element.1010

Another thing we can do is add text.1024

This is just another method: you add some text here as the first parameter, and then these two parameters are the location.1034

And there you see: it says "Hello world."1044

And I can't select it, because it is kind of an image; it is in the canvas.1047

That is just a few really basic things you can do to the canvas, but you can get a lot more complicated.1052

Here is an example I created yesterday; and I am going to zoom in.1059

First of all, I put that image again; but it is much wider than the canvas screen actually is.1066

So, what I am going to do is scroll it to the left.1076

And I also put a little rectangle here that is blue and somewhat transparent.1079

And even though I have set this in terms of the number of pixels from the left and the top,1086

because it is relative to the canvas, I can actually (using some other JavaScript) increase the size of the canvas.1094

This is just using CSS to increase the size of the canvas, just so you can see a little better.1100

And now, I have also set up so that, when I click on this, it will do this little thing where I can control the square's location with my arrow keys.1106

And it is transparent, so you can kind of see the buildings through it.1121

And you can imagine how I can develop this into a side-scrolling game--something like where you are shooting little aliens or whatever.1124

There is a lot that you can do with this; and this took me just probably half an hour of coding to put this together, and come up with the idea, and everything.1133

And I can increase the speed; and if I wanted to put a little more effort into it,1145

I could have loaded a little spaceship (or something) image, instead of just the square.1148

And basically, the only limits are what you can think of for the canvas element.1154

That is that; thanks for watching