Home >Web Front-end >HTML Tutorial >Self-study HTML5 Section 4 (detailed explanation of canvas)_html/css_WEB-ITnose

Self-study HTML5 Section 4 (detailed explanation of canvas)_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-24 11:56:401123browse

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

What is 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()

Line

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

Circle

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

Gradient

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

Image

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

  

Statement:
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