HTML5小练习之canvas画图练习,画一个数学sin函数:

效果图如下:

HTML5——canvas小练习——函数图

代码:

<!DOCTYPE html>
<html>
<head>
    <!-- Css样式 -->
    <style type="text/css">
        .mainone {
            display: inline-block;
        }
        .headone {
            margin-left: 280px;
        }
        #MyCanvas {
            background-color: #fbd0d0;
            margin-left: 200px;
        }

    </style>

    <script type="text/javascript">
        function draw(){
            var my_canvas = document.getElementById( "MyCanvas" );
            var co = my_canvas.getContext( "2d" );
            co.translate(10, 110);
            co.beginPath();
            co.strokeStyle = '#000000';   //设定线条颜色
            co.lineWidth = 0.5;       //设定线条宽度,预设为1
            co.lineCap = 'round';     //设定线头格式
            //画一条水平的线
            co.moveTo(-10, 0);
            co.lineTo(220, 0);  //从x点到y点
            //画一条垂直的线
            co.moveTo(0, -110);
            co.lineTo(0, 110);
            co.closePath();
            co.stroke();  //绘制边线
            //画出多条虚线
            co.setLineDash([2, 6]);
            co.moveTo(-10, -100);
            co.lineTo(220, -100);
            co.moveTo(-10, 100);
            co.lineTo(220, 100);
            co.moveTo(100, -110);
            co.lineTo(100, 110);
            co.moveTo(200, -110);
            co.lineTo(200, 110);
            co.closePath();
            co.stroke();  // 绘制边线
            //设定坐标文字
            co.font = "8pt Aprial";
            var ff = 10;
            co.fillText("0", 0, ff);
            co.fillText("π", 100, ff);
            co.fillText("2π", 200, ff);
            co.fillText("+1", 0, -100 + ff);
            co.fillText("-1", 0, +100 + ff);
            //绘制曲线
            co.beginPath();
            co.lineWidth = 1;       //设定线条宽度,预设为1
            co.setLineDash([]);      //设置线条为实线
            co.lineCap = 'round';     //设定线头格式
            co.moveTo(0, 0);
            for (var i = 0; i < 200; i ++) {
                co.lineTo(i, Math.sin(i/100*Math.PI)*(-100));
            }
            co.stroke();
            co.closePath();

        }
       
    </script>
</head>
<body onload="draw()">
    <div class="mainone">
        <h3 class="headone">Sin(x)</h3>
        <canvas id="MyCanvas" width="280" height="260"></canvas>
    </div>
    

</body>
</html>

 

相关文章:

  • 2022-12-23
  • 2021-09-08
  • 2021-10-11
  • 2021-08-14
  • 2022-12-23
  • 2021-11-30
  • 2021-08-14
  • 2022-01-25
猜你喜欢
  • 2022-12-23
  • 2022-01-03
  • 2022-01-14
  • 2021-12-16
  • 2021-09-19
  • 2022-01-06
相关资源
相似解决方案