`
lucifinilhades
  • 浏览: 84748 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

HTML5 绘制图形【1】

阅读更多

canvas元素基础

canvas元素是HTML5中新增的一个重要元素,专门用来绘制图形。在页面上放置一个canvas元素,就相当于在页面上放置了一块“画布”,可以在其中进行图形的描绘。canvas元素只是一块无色透明的区域。需要利用JavaScript编写在其中进行绘画的脚本。

在页面中放置canvas元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8"/>
		<title>canvas元素示例</title>
		<script type="text/javascript" src="jquery.js"></script>
		<script type="text/javascript" src="canvas.js"></script>
	</head>
	<body>
		<h1>canvas元素示例</h1>
		<canvas id="draw" width="400" height="400"></canvas>
	</body>
</html>

绘制矩形

用canvas元素绘制图形需要经过的步骤如下:

  1. 取得canvas元素;
  2. 取得上下文(context):进行图形绘制时需要用到图形上下文(graphics context),图形上下文中是一个封装了很多绘图功能的对象。需要使用canvas对象的getContext()方法来获得图形上下文,并将参数设置为"2d";
  3. 填充与绘制边框:填充是指填满图形内部、绘制边框是指不填满图形内部,只绘制图形的外框。canvas元素结合使用这两种方式来绘制图形;
  4. 设定绘制图样式(style):在进行图形绘制时,首先要设定好绘图的样式,然后调用有关方法进行图形的绘制。所谓绘图的样式,主要是针对图形的颜色而言的,但是并不限于图形的颜色,例如:设定填充图形的样式使用fillStyle属性、设定图形边框的样式使用strokeStyle属性;
  5. 指定线宽:使用图形上下文对象的lineWidth属性设置图形边框的宽度。在绘制图形的时候,任何直线都可以通过lineWidth属性来指定宽度;
  6. 指定颜色值:绘图时填充颜色或边框的颜色分别通过fillStyle属性和strokeStyle属性来指定。颜色值使用的是普通样式表中使用的颜色值(包括颜色名称、颜色十六进制值),另外也可以通过rgb()或rgba()函数来指定颜色值;
  7. 绘制图形:分别使用fillRect()方法和strokeRect()方法来填充矩形和绘制矩形边框。
context.fillRect(x, y, width, height);
context.strokeRect(x, y, width, height);
context.clearRect(x, y, width, height);

这里的context指的是图形上下文对象,最后一个clearRect()方法将擦除指定的矩形区域中的图形,使得矩形区域中的颜色全部变为透明。

为了使用方便,将上述方法及属性封装进自定义的Canvas对象,该对象定义如下:

function Canvas(id) {
	this.id = id;
	this.canvas = document.getElementById(id);
	this.context = this.canvas.getContext('2d');
}

Canvas.prototype.fillStyle = function(style) {
	this.context.fillStyle = style;
	return this;
};

Canvas.prototype.strokeStyle = function(style) {
	this.context.strokeStyle = style;
	return this;
};

Canvas.prototype.lineWidth = function(width) {
	this.context.lineWidth = width;
	return this;
};

Canvas.prototype.fillRect = function(x, y, width, height) {
	this.context.fillRect(x, y, width, height);
	return this;
};

Canvas.prototype.strokeRect = function(x, y, width, height) {
	this.context.strokeRect(x, y, width, height);
	return this;
};

Canvas.prototype.clearRect = function(x, y, width, height) {
	this.context.clearRect(x, y, width, height);
	return this;
};

使用该自定义对象绘制图形示例如下:

$(function() {
	var canvas = new Canvas($("canvas").attr("id"));
	canvas.fillStyle("#EEEEFF").fillRect(0, 0, 400, 400).fillStyle("red").strokeStyle("blue").lineWidth(1).fillRect(50, 50, 100, 100).strokeRect(50, 50, 100, 100);
});		
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics