日期:2014-05-17  浏览次数:20719 次

2维函数绘图 html5版

?

?

?

<html>
	<head>
		<script type="text/javascript">
			//var cxt=document.getElementById(drawplane).getContext("2d");
			
			function plot(canvasid,fun,x1,x2,y1,y2){
				var cvs=document.getElementById(canvasid);
				var cxt=cvs.getContext('2d');
				
				var cvs_width=cvs.width;
				var x_width=x2-x1;
				var x_to_cvs_rate=cvs_width/x_width;
				
				var cvs_height=cvs.height;
				var y_height=y2-y1;
				var y_to_cvs_rate=cvs_height/y_height;
				
				//function cvs_to_x(left){
					//cvs_left
				//}
				
				//初始化绘图
				var cvs_top=0;
				var y=0;
				var cvs_left0=x1*x_to_cvs_rate;
				var cvs_left1=x2*x_to_cvs_rate;
				cxt.translate(-cvs_left0,cvs_height/2);
				cxt.scale(1,-1);
				var cvs_left0=x1*x_to_cvs_rate;
				var cvs_left1=x2*x_to_cvs_rate;
				for(var cvs_left=cvs_left0;cvs_left<=cvs_left1;cvs_left++){
						//计算
						x=cvs_left/x_to_cvs_rate;
						y=fun(x);
						cvs_top=y*y_to_cvs_rate;
						//绘图
						cxt.lineTo(cvs_left,cvs_top);
				}
				cxt.stroke();
			}
			
			function init(){
				plot("drawplane",Math.abs,-10,10,-1,1);
			}
			window.onload=init;
		</script>
	</head>
	<body>
		<canvas id="drawplane" style="border:solid 1px red"></canvas>
	</body>
</html>
?

?

?

?

?

?

?

?

?

?

?

?