如何使用html5的canvas 做一个曲线图----y= cos(x)曲线制作
1个回答
展开全部
<!DOCTYPE html>
<html>
<head>
<title>Cos演示</title>
<meta charset='utf-8'>
</head>
<body style='text-align:center'>
<canvas width='800' height='600' id='canvas' style='border:1px solid'>
</canvas>
<script>
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext('2d');
function drawAxis(){
ctx.translate(400,300);
//x 轴
ctx.beginPath();
ctx.moveTo(-380,0);
ctx.lineTo(380,0);
ctx.lineTo(372,3);
ctx.lineTo(372,-3);
ctx.lineTo(380,0);
ctx.stroke(); //描边
//y 轴
ctx.moveTo(0,200);
ctx.lineTo(0,-200);
ctx.lineTo(3,-192);
ctx.lineTo(-3,-192);
ctx.lineTo(0,-200);
ctx.stroke(); //描边
//画坐标
ctx.save();
ctx.strokeStyle='rgba(100,100,255,0.5)';
ctx.moveTo(-Math.PI*100,100);
ctx.lineTo(-Math.PI*100,-100);
ctx.lineTo(Math.PI*100,-100);
ctx.lineTo(Math.PI*100,100);
ctx.lineTo(-Math.PI*100,100);
ctx.stroke(); //描边
ctx.fillStyle='rgba(0,0,0,1)';
ctx.fillText("-π",-Math.PI*100,10);
ctx.fillText("π",Math.PI*100,10);
ctx.fillText("-1",5,100);
ctx.fillText("1",5,-100);
ctx.restore();
}
function drawCos(){
var x = -Math.PI*100;
ctx.beginPath();
ctx.moveTo(x,100);
for(x = -Math.PI*100;x<Math.PI*100;x++){
var cx = x/100;
var cy = Math.cos(cx);
var y = -cy*100;
ctx.lineTo(x,y);
}
ctx.stroke(); //描边
}
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.shadowColor='rgba(0,0,0,0.8)';
ctx.shadowOffsetX=12;
ctx.shadowOffsetY=12;
ctx.shadowBlur=15;
drawAxis();
drawCos();
ctx.restore();
}
ctx.fillStyle='rgba(100,140,230,0.5)';
ctx.strokeStyle='rgba(33,33,33,1)';
draw();
</script>
</body>
</html>
代码附上,妥妥的~
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询