Links Link Colors Link Bookmarks. PI ; ctx. Report Error. Your message has been sent to W3Schools. W3Schools is optimized for learning and training.
Examples might be simplified to improve reading and learning. However, all of these properties and methods are used in conjunction with current state , a concept that must be grasped before you can really understand how to work with HTML5 Canvas. The current state is actually a stack of drawing states that apply globally to the entire canvas. You will manipulate these states when drawing on the canvas.
These states include:. Methods for scale, rotate, transform, and translate. Created with the clip method.
We will discuss these properties in depth in the next three chapters. Remember earlier in this chapter when we discussed immediate mode versus retained mode? The canvas is an immediate mode drawing surface, which means everything needs to be redrawn every time something changes.
There are some advantages to this; for example, global properties make it very easy to apply effects to the entire screen. Once you get your head around it, the act of redrawing the screen every time there is an update makes the process of drawing to the canvas straightforward and simple. On the other hand, retained mode is when a set of objects is stored by a drawing surface and manipulated with a display list. Flash and Silverlight work in this mode.
Retained mode can be very useful for creating applications that rely on multiple objects with their own independent states. Many of the same applications that could make full use of the canvas games, activities, animations are often easier to code with a retained mode drawing surface, especially for beginners.
Our challenge is to take advantage of the immediate mode drawing surface, while adding functionality to our code to help it act more like it works in retained mode.
Throughout this book we will discuss strategies that will help take this immediate mode operation and make it easier to manipulate through code. You can also create an instance of a canvas in code like this:. The Canvas object has two associated properties and methods that can be accessed through JavaScript: width and height. These tell you the current width and height of the canvas rendered on the HTML page.
It is important to note that they are not read-only; i. What does this mean? It means you can dynamically resize the canvas on the HTML page without reloading. You can also use CSS styles to change the scale of the canvas. Unlike resizing, scaling takes the current canvas bitmapped area and resamples it to fit into the size specified by the width and height attributes of the CSS style.
We include an example of scaling the Canvas with a transformation matrix in Chapter 3. There are also two public methods for the Canvas object. The first is getContext , which we used earlier in this chapter. We will continue to use it throughout this book to retrieve a reference to the Canvas 2D context so we can draw onto the canvas. The second property is toDataURL. This method will return a string of data that represents the bitmapped image of the Canvas object as it is currently rendered.
By supplying different MIME types as a parameter, you can retrieve the data in different formats. We will use the toDataURL in the next application to export an image of the canvas into another browser window. The game keeps track of how many guesses the player has made, lists the letters he has already guessed, and tells the player whether he needs to guess higher toward Z or lower toward A.
We use a drawScreen function to render text on the canvas. However, there are some other functions included as well, which are described next. Here is a rundown of the variables we will use in the game. They are all defined and initialized in canvasApp , so they have scope to the encapsulated functions that we define locally.
This variable holds the number of times the player has pressed a letter. The lower the number, the better he has done in the game. The content of this variable is displayed to give the user instructions on how to play.
This array holds one of each letter of the alphabet. We will use this array to both randomly choose a secret letter for the game, and to figure out the relative position of the letter in the alphabet. This variable holds the current date. It is displayed on the screen but has no other purpose. This array holds the current set of letters the player has guessed already. We will print this list on the screen to help the player remember what letters he has already chosen.
This variable is set to false until the player wins. The initGame function sets up the game for the player. The two most important blocks of code are as follows. This code finds a random letter from the letters array and stores it in the letterToGuess variable:. This code adds an event listener to the window object of the DOM to listen for the keyboard keyup event.
When a key is pressed, the eventKeyPressed event handler is called to test the letter pressed:. This function, called when the player presses a key, contains most of the action in this game. Every event handler function in JavaScript is passed an event object that has information about the event that has taken place. We use the e argument to hold that object.
The first test we make is to see whether the gameOver variable is false. If so, we continue to test the key that was pressed by the player; the next two lines of code are used for that purpose. The first line of code gets the key-press value from the event, and converts it to an alphabetic letter that we can test with the letter stored in letterToGuess :.
The next line of code converts the letter to lowercase so that we can test uppercase letters if the player unintentionally has Caps Lock on:. Next, we increase the guesses count to display, and use the Array. Now it is time to test the current game state to give feedback to the player. First, we test to see whether letterPressed is equal to letterToGuess. If so, the player has won the game:. If the player has not won, we need to get the index of letterToGuess and the index of letterPressed in the letters array.
Because we alphabetized the letters in the array, it is very easy to test which message to display:. Now we make the test. First, if guessIndex is less than zero, it means that the call to indexOf returned -1 , and the key press was not a letter. We then display an error message:. The rest of the tests are simple. Now we get to drawScreen. We only set context. Also, we change the color using context.
The most interesting thing we display here is the content of the lettersGuessed array. On the canvas, the array is printed as a set of comma-separated values, like this:. To print this value, all we do is use the toString method of the lettersGuessed array, which prints out the values of an array as—you guessed it—comma-separated values:.
We also test the gameOver variable. If it is true , we put You Got It! Earlier, we briefly discussed the toDataUrL property of the Canvas object.
We are going to use that property to let the user create an image of the game screen at any time. This acts almost like a screen-capture utility for games made on Canvas.
However, you can create a fully enclosed arc such as circle using the arc method. The default color of the stroke is black and its thickness is one pixel. But, you can set the color and width of the stoke using the strokeStyle and lineWidth property respectivley.
You can also set the cap style for the lines using the lineCap property. There are three styles available for the line caps — butt, round, and square. Here's an example:. Tip: While styling the shapes on canvas, it is recommended to use the fill method before the stroke method in order to render the stroke correctly.
Similarly, you can use the fillStyle method to fill solid color inside a circle too. You can also fill gradient color inside the canvas shapes. A gradient is just a smooth visual transition from one color to another. There are two types of gradient available — linear and radial.
The following example uses the createLinearGradient method to fill a linear gradient color inside a rectangle. Let's try it out to understand how it basically works:. Similarly, you can fill canvas shapes with radial gradient using the createRadialGradient method. The basic syntax for creating a radial gradient can be given with:.
The following example uses the createRadialGradient method to fill a radial gradient color inside a circle. Let's try it out to understand how it actually works:.
0コメント