First, create a canvas
1 <!DOCTYPE HTML>2 <HTML>3 <HeadLang= "en">4 <MetaCharSet= "UTF-8">5 <title></title>6 </Head>7 8 <Body>9 <CanvasID= "Canvas"width= "1024x768"Height= "768"style= "border:1px solid #aaa; display:block;margin:30px auto;"></Canvas>Ten <!-- One Description: A 1. It is not recommended to use CSS to set width and height for canvas, because canvas has not only the size of the canvas display, but also the resolution of the picture it displays inside it . - 2. Note Width and height do not add unit px - - the </Body> - </HTML>
Typically there are two parts: HTML and JavaScript
Html
<id= "Canvas"></canvas>
Javascript
1 var canvas=document.getelementbyid (' canvas '); 2 var context=canvas.getcontext (' 2d '); 3 // draw using the context
Example:
1 <!DOCTYPE HTML>2 <HTML>3 <HeadLang= "en">4 <MetaCharSet= "UTF-8">5 <title></title>6 </Head>7 8 <Body>9 <CanvasID= "Canvas"style= "border:1px solid #aaa; display:block;margin:30px auto;">Ten the current browser does not support canvas, please change your browser One </Canvas> A <Script> - varCanvas=document.getElementById ('Canvas'); - Canvas.width=1024x768; the Canvas.height=768;//You can also set the width and height here - varContext=Canvas.getcontext ('2d'); - //draw using the context - </Script> + <!-- - Description: + 1. To consider browser compatibility issues, prompt in the Canvas tab, when the browser supports canvas, the text inside will be ignored A 2. Browser-compatible judgments can also be made in JS. The judgment is displayed in the following code block at - - </Body> - </HTML>
Using JS hint compatibility
1 <Script>2 varCanvas=document.getElementById ('Canvas'); 3 Canvas.width=1024x768;4 Canvas.height=768;//You can also set the width and height here5 6 if(Canvas.getcontext ("2d")){7 varContext=Canvas.getcontext ('2d');8 //draw using the context9 }Else{Ten Alert ('the current browser does not support canvas, please change your browser and try again') One } A </Script>
Learn the basics of canvas drawing and animation (I.)