---
title: "Html5 系列之:Canvas绘图"
author: "lexinquan"
date: "2012-11-16T16:39:00Z"
tags: []
slug: "html5-canvas"
draft: false
lastmod: "2012-11-16T17:15:39Z"
id: 1728097
url: "https://lexinquan.iteye.com/blog/1728097"
---

Canvas是什么？它能做什么？简单的说Canvas是一个容器，可以往里面添加各种内容，如图片，绘制图形，甚至添加另外一个Canvas。各浏览器对Canvas的支持对比图：![Canvas](http://img.my.csdn.net/uploads/201211/16/1353056483_7793.png)先看一个简单的例子：

```
//创建一个canvas对象
var canvas = document.createElement('canvas');
canvas.height = 100;
canvas.width = 300;
//获取canvas上下文环境
ctx = canvas.getContext('2d');

  //画一个矩形，并用fillstyle来填充
ctx.fillStyle ="#3e4";
ctx.fillRect(20,20,50,50);
```

下面通过例子来看看canvas有哪些方法。

```
//也可创建一个，如newCanvas（）；
	var canvas  =document.querySelector("#canvas1");

	//获取canvas上下文环境
	ctx = canvas.getContext('2d');

	//画一个矩形，并用fillstyle来填充
	ctx.fillStyle ="#3e4";
	ctx.fillRect(20,20,50,50);

	//设置线条颜色
	ctx.strokeStyle ="#00f0f0";
	//画一个矩形边缘
	ctx.strokeRect(10,10,100,100);

	//画一条线
	ctx.beginPath();
	ctx.moveTo(40,40);
	ctx.lineTo(500,300);

	ctx.strokeStyle ="red";
	ctx.stroke();//关键

	//添加一些文字
	ctx.font="bold 16px";
	ctx.fillText("Hello Html5",250,250);

	//添加图片
	var img = new Image();
	img.src="images/google-logo-small.png";
	img.onload = function(){
		ctx.drawImage(img,300,100);
		ctx.drawImage(img,350,200);
	}

//画一段弧线
	ctx.beginPath();
    ctx.arc(650, 110, 100, Math.PI * 1/2, Math.PI * 3/2);
    ctx.lineWidth = 15;
    ctx.lineCap = 'round';
    ctx.strokeStyle = 'rgba(255, 127, 0, 0.5)';
    ctx.stroke();
```

![result](http://img.my.csdn.net/uploads/201211/16/1353056483_2054.png)网上的一些实例：Canvas绘制loading图像： http://html5demos.com/canvasCanvas 2dcontext接口参考：http://dev.w3.org/html5/2dcontext/Overview.html