码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript高级程序设计:Canvas绘图

时间:2015-03-16 16:11:02      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

Canvas 绘制矩形

var drawing = document.getElementById(‘drawing‘);

		if( drawing.getContext ){

			var context = drawing.getContext(‘2d‘);
			
			// 绘制矩形
			context.fillStyle = ‘#0000ff‘;
			context.fillRect( 10, 10 , 50 , 50 );

			// 绘制半透明红色矩形
			context.fillStyle = ‘rgba(255,0,0,0.5)‘;
			context.fillRect( 30, 30, 50, 50);

			// 绘制描边矩形
			context.lineWidth = 1;
			context.strokeStyle = ‘#000000‘;
			context.strokeRect( 50 , 50, 50, 50 );

			// 清除一个小矩形
			context.clearRect( 40,40,10,10 );
		}

Canvas 绘制路径

var drawing = document.getElementById(‘drawing‘);

		if( drawing.getContext ){

			var context = drawing.getContext(‘2d‘);

			// 开始路径
			context.beginPath();

			// 绘制外圆
			context.arc( 100 , 100 , 99 , 0 , 2 * Math.PI , false );

			// 绘制内圆
			context.moveTo(194,100);
			context.arc( 100 , 100 , 94 , 0 , 2 * Math.PI , false );

			// 变换坐标原点
			//context.translate(100,100);

			// 旋转原点
			//context.rotate(1);

			// 绘制分针
			context.moveTo(100,100);
			context.lineTo(100,15);

			// 绘制时针
			context.moveTo(100,100);
			context.lineTo(35,100);

			//
			context.stroke();

			// 绘制文本
			context.font = "bold 14px ‘Arial‘";
			context.textAlign = "center";
			context.textBaseline = "middle";
			context.fillText("12",100,20);
		}

Canvas 使用图像数据

window.onload = function(){

			var drawing = document.getElementById(‘drawing‘);

			if( drawing.getContext ){

				var context = drawing.getContext("2d"),
					image = document.getElementById(‘tulip‘),
					imageData , data,
					i, len, average,
					red, green, blue, alpha;

				// 绘制原始图像
				context.drawImage( image , 10 , 10 );
				
				// 获得图像数据
				imageData = context.getImageData(0,0,image.width,image.height);
				data = imageData.data;


				for( i=0, len=data.length; i<len; i+=4 ){

					red = data[i];
					green = data[i+1];
					blue = data[i+2];
					alpha = data[i+3];

					// 获得 rgb 平均值
					average = Math.floor( (red+green+blue) / 3 );

					// 配置颜色值, 透明度不变
					data[i] = average;
					data[i+1] = average;
					data[i+2] = average;
				}

				// 回写图像数据
				imageData.data = data;
				context.putImageData( imageData , 400 , 400 );
			}
		}

JavaScript高级程序设计:Canvas绘图

标签:

原文地址:http://www.cnblogs.com/yangke687/p/4341919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!