The canvas element is used to draw graphics on web pages.
What is Canvas?
HTML 5’s canvas element uses JavaScript to draw images on the web page.
The canvas is a rectangular area that you can control every pixel of.
canvas has multiple ways to draw paths, rectangles, circles, characters, and add images.
Create Canvas element
Add canvas element to HTML 5 page, specify the element's id, width and height:
<canvas id="myCanvas" width="200" height="100"></canvas>
Draw through JavaScript
The canvas element itself has no drawing capabilities. All drawing work must be done inside JavaScript:
<script type="text/javascript"> var c=document.getElementById("myCanvas"); var cxt=c.getContext("2d"); cxt.fillStyle="#FF0000"; cxt.fillRect(0,0,150,75); </script>
JavaScript uses the id to find the canvas element:
var c=document.getElementById("myCanvas");
Then, create the context object:
var cxt=c.getContext("2d");
getContext("2d") The object is a built-in HTML 5 object with many Ways to draw paths, rectangles, circles, characters, and add images.
Example: Hover the mouse over the rectangle to see the coordinates. Try it yourself. The code is as follows:
<!DOCTYPE HTML> <html> <head> <style type="text/css"> body { margin: 0px; font-size: 70%; font-family: verdana, helvetica, arial, sans-serif; } #coordiv { float: left; width: 199px; height: 99px; border: 1px solid #c3c3c3 } </style> <script type="text/javascript"> function cnvs_getCoordinates(e) { x=e.clientX; y=e.clientY; document.getElementById("xycoordinates").innerHTML="Coordinates: (" + x + "," + y + ")"; } function cnvs_clearCoordinates() { document.getElementById("xycoordinates").innerHTML=""; } </script> </head> <body> <p>把鼠标悬停在下面的矩形上可以看到坐标:</p> <div id="coordiv" onmousemove="cnvs_getCoordinates(event)" onmouseout="cnvs_clearCoordinates()"></div> <div id="xycoordinates"></div> </body> </html>
The above is the content of the Canvas element in HTML5. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!