canvas画矩形(包括渐变)

index.html内容:

<!DOCTYPE HTML>
<html>
<style type="text/css">
#myCanvas {border: 1px solid #BEBEBE;}
</style>
<body>
    <canvas id="myCanvas" width="800" height="600">你的浏览器不支持 HTML5</canvas>
    <script src="index.js"></script>
</body>

</html>

index.js内容:

(function(){ // 闭包,防止变量、方法重复
	var canvasDom = document.getElementById("myCanvas");
	var context = canvasDom.getContext("2d"); // 获取绘制功能的对象(context:上下文)
	
	drawRectangle(10, 10, 300, 200, 10, ['red', 'blue']);
	/**
	 * [drawRectangle 画一个空心的矩形]
	 * @param  {[int]} x      [起点x坐标]
	 * @param  {[int]} y      [起点y坐标]
	 * @param  {[int]} width  [宽度]
	 * @param  {[int]} height [高度]
	 * @param  {[int]} lineWidth  [线宽]
	 * @param  {[string]} color  [边框颜色,如果是数组,则渐变]
	 * @param  {[int]} direction [渐变方向:0-左右;1-上下;2-左上到右下;3-左下到右上]
	 * @return {[undefined]}        [无]
	 */
	function drawRectangle(x, y, width, height, lineWidth, color, direction) {
		context.beginPath(); // 开始路径,如果没有这个和结束路径包围,所有线条都是最后那根线条的样式了
		
		context.strokeStyle = getFillColor(x, y, width, height, color, direction);
		context.lineWidth = lineWidth;
		context.strokeRect(x, y, width, height);
		
		context.closePath(); // 结束路径,应与开始路径呼应(会不会导致内存泄露跟实现有关系)
		context.stroke();
	}
	
	fillRectangle(10, 220, 300, 200, ['blue', 'green'], 3);
	/**
	 * [fillRectangle 画一个实心的矩形]
	 * @param  {[int]} x      [起点x坐标]
	 * @param  {[int]} y      [起点y坐标]
	 * @param  {[int]} width  [宽度]
	 * @param  {[int]} height [高度]
	 * @param  {[string|array]} color  [填充颜色,如果是数组,则渐变]
	 * @param  {[int]} direction [渐变方向:0-左右;1-上下;2-左上到右下;3-左下到右上]
	 * @return {[undefined]}        [无]
	 */
	function fillRectangle(x, y, width, height, color, direction) {
		context.beginPath(); // 开始路径,如果没有这个和结束路径包围,所有线条都是最后那根线条的样式了
		
		
		context.fillStyle = getFillColor(x, y, width, height, color, direction);
		context.fillRect(x, y, width, height);
		
		context.closePath(); // 结束路径,应与开始路径呼应(会不会导致内存泄露跟实现有关系)
		context.stroke();
	}
	
	function getFillColor(x, y, width, height, color, direction) {
		var fillColor = color;
		if (typeof color == 'object') {
			var x1 = x, y1 = 0;
			var x2 = x+width, y2 = 0;
			if (direction == 1) {
				x1 = 0; y1 = y;
				x2 = 0; y2 = y+height;
			} else if (direction == 2) {
				x1 = x; y1 = y;
				x2 = x+width; y2 = y + height;
			} else if (direction == 3) {
				x1 = x; y1 = y+height;
				x2 = x+width; y2 = y;
			}
			fillColor = context.createLinearGradient(x1, y1, x2, y2);
			for (var i=0; i<color.length; i++) {
				fillColor.addColorStop(i/color.length, color[i]);
			}
		}
		return fillColor;
	}
	
})();

相关推荐