Let’s start with the definition of the
<canvas id="myCanvas" width="150" height="150"></canvas>
Copy after login
The closing tag is required. The
<canvas id="game" width="150" height="150">
Oh dear, your browser dosen't support HTML5! Tell you what, why don't you upgrade to a decent browser - you won't regret it!</canvas>
<canvas id="clock" width="150" height="150">
<imgsrc="images/clock.png" width="150" height="150"/>
</canvas>
Copy after login
The fixed-size drawing screen created opens one or more rendering contexts (rendering context), through which we can control the content to be displayed. We focus on 2D rendering, which is currently the only option, and may add an OpenGL ES-based 3D context in the future.
The initialization is blank. To draw with a script on it, you first need its rendering context. It can be obtained through the getContext
method of the canvas element object. At the same time, the obtained There are some functions for drawing. getContext()
Accepts a value describing its type as a parameter. getContext() returns a CanvasRenderingContext2D object.
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
Copy after login
The first line above obtains the DOM node of the canvas object through the getElementById method. Then obtain its drawing operation context through its getContext
method.
In addition to displaying alternative content on browsers that do not support canvas, you can also use scripts to check whether the browser supports canvas. The method is very simple, just determine whether getContext
exists. var canvas = document.getElementById('myCanvas');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
Copy after login
We will start with the following simplest code template (which will be used in subsequent examples).
Canvas tutorial
<canvas id="myCanvas" width="150" height="150"></canvas>
Copy after login
If you are careful, you will find that I have prepared a function named draw
, which will be executed once after the page is loaded (by setting the onload attribute of the body tag). Of course, it can also be used in other is called in the event handler function.
The above is one of canvas game development learning: first introduction to the content of the tag. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!