Canvas seems to be the essence of HTML5. You must learn it well. Well, beautiful things must start from the basics. . . .
Let’s first look at what is called canvas
HTML5’s canvas element uses JavaScript to draw images on a web page.
The canvas is a rectangular area that you can control every pixel of.
Canvas has many ways to draw paths, rectangles, circles, characters and add images.
Create a canvas
Add canvas element to HTML5 page.
Specifies the id, width and height of the element:
<canvas id="myCanvas" width="200" height="100"></canvas><strong>矩形的绘制</strong>
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"); //使用 id 来寻找 canvas 元素:var cxt=c.getContext("2d"); //创建 context 对象:getContext("2d") 对象是内建的 HTML5 对象,拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法cxt.fillStyle="#FF0000"; //代码绘制一个红色的矩形: cxt.fillRect(0,0,150,75);</script>
1. fillRect()
2. strokeRect()
specified by Where to start and where to end to draw a line:
<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");cxt.moveTo(10,10);cxt.lineTo(150,50);cxt.lineTo(10,50);cxt.stroke();</script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the canvas element.</canvas>1. lineWidth
<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");cxt.fillStyle="#FF0000";cxt.beginPath();cxt.arc(70,18,15,0,Math.PI*2,true);cxt.closePath();cxt.fill();</script>
<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");var grd=cxt.createLinearGradient(0,0,175,50);grd.addColorStop(0,"#FF0000");grd.addColorStop(0.5,"#00FF00");grd.addCOlorStop(1,"#212121");cxt.fillStyle=grd;cxt.fillRect(0,0,175,50);</script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the canvas element.</canvas>
<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");var img=new Image()img.src="flower.png"cxt.drawImage(img,0,0);</script>