Home > Web Front-end > H5 Tutorial > body text

Canvas element in HTML5

黄舟
Release: 2016-12-22 15:27:15
Original
1388 people have browsed it

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>
Copy after login

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>
Copy after login

JavaScript uses the id to find the canvas element:

var c=document.getElementById("myCanvas");
Copy after login

Then, create the context object:

var cxt=c.getContext("2d");
Copy after login

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>
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template