JavaScript图形实例:曲线方程
JavaScript图形实例:曲线方程
在HTML5 Canvas画布中,我们可以根据曲线的方程绘制出曲线。例如,在笛卡尔坐标系中,圆的方程为:
x=r*cos(θ)
y=r*sin(θ) (0≤θ≤2π)
编写如下的HTML代码。
function draw(id)
{
var canvas=document.getElementById(id);
if (canvas==null)
return false;
var context=canvas.getContext('2d');
context.fillStyle="#EEEEFF";
context.fillRect(0,0,300,300);
context.strokeStyle="red";
context.lineWidth=2;
context.save();
context.translate(150,150);
var r=100;
context.beginPath();
for (theta=0;theta<=2*Math.PI;theta+=Math.PI/100)
{
var x = r*Math.cos(theta); // 圆的方程式
var y = r*Math.sin(theta);
if (theta==0)
context.moveTo(x,y);
else
context.lineTo(x,y);
}
context.stroke();
context.restore();
}
在浏览器中打开包含这段HTML代码的html文件,可以看到在浏览器窗口中,绘制出一个圆心位于(150,150),半径为100的圆。
若将HTML文件中的圆的方程改写为:
var x = 100*Math.cos(theta); // 椭圆方程
var y = 75*Math.sin(theta);
则在浏览器窗口中绘制出一个椭圆。
下面我们给出采用曲线方程绘制的各类曲线实例。
1.星形线
星形线的笛卡尔坐标方程式为:
x=r*cos(θ)^3
y=r*sin(θ)^3 (0≤θ≤2π)
编写如下的HTML代码。
function draw(id)
{
var canvas=document.getElementById(id);
if (canvas==null)
return false;
var context=canvas.getContext('2d');
context.fillStyle="#EEEEFF";
context.fillRect(0,0,300,300);
context.strokeStyle="red";
context.lineWidth=2;
context.save();
context.translate(150,150);
var r=80;
context.beginPath();
for (a=0;a<=2*Math.PI;a+=Math.PI/100)
{
var x = r*Math.cos(a)*Math.cos(a)*Math.cos(a);
var y = r*Math.sin(a)*Math.sin(a)*Math.sin(a);
if (a==0)
context.moveTo(x,y);
else
context.lineTo(x,y);
}
context.stroke();
context.restore();
}