canvas的线形基本用法+ 绘制折线图

canvas的线形基本用法+ 绘制折线图

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>canvas</title>
  <style>
     canvas{
        border:1px solid #eee;
     }
  </style>
</head>
<body>
    <!-- 准备画布,要在canvas元素本身上设置大小 -->
    <canvas width="1000" height="1000">

    </canvas>
    <script>
        //  获取元素
         var mycanvas = document.querySelector('canvas') 
        // 获取上下文,绘制工具箱
         var ctx =mycanvas.getContext('2d');

        //绘制线条
        //移动画笔,设置起点,
        //默认宽度1px,默认颜色 黑色,但实际上有出入
        //原因:对齐的点事线的中心位置,会把线分成两个0.5px,显示的是会不饱和增加宽度
        //解决方法:前后移动0.5px
        ctx.beginPath();//开始新路径
        ctx.moveTo(100,100.5);
        //绘制轨迹,绘制路径
        ctx.lineTo(300,20);
        ctx.lineTo(300,100.5);
        ctx.strokeStyle="red";//描边的颜色(样式会覆盖)
        ctx.lineWidth =20; //描边的宽度
        ctx.lineCap = 'round'; //设置线两端样式
        ctx.lineJoin= 'round'
        //描轨迹,描边
        ctx.stroke();

        ctx.beginPath();//开始新路径
        ctx.moveTo(100,200.5);
        ctx.lineTo(200,120);
        ctx.lineTo(300,200.5);
        ctx.strokeStyle="blue";//描边的颜色
        ctx.lineWidth =10; //描边的宽度
        ctx.lineCap = 'square';
        ctx.lineJoin = 'bevel'
         //描轨迹,描边
        ctx.stroke();

        ctx.beginPath();//开始新路径
        ctx.moveTo(100,300.5);
        ctx.lineTo(300,300.5);
        ctx.strokeStyle="green";//描边的颜色(样式会覆盖)
        ctx.lineWidth =5; //描边的宽度
        ctx.lineCap = 'butt';
        ctx.lineJoin = ''
        //描轨迹,描边
        ctx.stroke();

        //绘制填充三角形
        ctx.moveTo(100,400);
        ctx.lineTo(200,400);
        ctx.lineTo(200,500)
        // ctx.lineTo(100,100);//起始点和linto的结束点无法完全闭合会缺角
        //所以要使用canvas的自动闭合
        ctx.closePath();
        ctx.stroke();
        //填充
        ctx.fillStyle ='pink'
        ctx.fill();

        //绘制镂空的正方形,逆时针转,
        //概念:非零填充(逆时针画正方形不填充,顺时针画正方形填充)
        ctx.beginPath();//开始新路径
        ctx.strokeStyle="red";//描边的颜色(样式会覆盖)
        ctx.moveTo(400,100);  
        ctx.lineTo(400,200);
        ctx.lineTo(500,200);
        ctx.lineTo(500,100);
        ctx.closePath();
        ctx.fill();
        ctx.fillStyle ='red'
        ctx.stroke();

        //设置虚线
        ctx.beginPath();//开始新路径
        ctx.moveTo(400,300.5);
        ctx.lineTo(600,300.5);
        ctx.strokeStyle="#aaa";//描边的颜色(样式会覆盖)
        //数组用来描述排列方式
        ctx.setLineDash([5,20,15]);
        //获取虚线的排列方式,获取的是不重复的那一段的排列方式
        console.log(ctx.getLineDash());
        //如果是正的值往后偏移,负值往前偏移
        ctx.lineDashOffset =20;
        ctx.stroke();


         //绘制一个从黑到白的渐变矩形
         //  获取元素
         var mycanvas = document.querySelector('canvas') 
        // 获取上下文,绘制工具箱
         var ctx =mycanvas.getContext('2d');
        // ctx.lineWidth =30;
        // for(var i=0;i<255;i++){
        //     ctx.beginPath();
        //     ctx.moveTo(100+i-1,100);
        //     ctx.lineTo(100+i,100);
        //     ctx.strokeStyle = 'rgb('+i+','+i+','+i+')';
        //     ctx.stroke();
        // }
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>canvas-折线图</title>
  <style>
      canvas{
         border:1px solid #aaa;
      }
  </style>
</head>
<body>
    <canvas width='800' height='400'>

    </canvas>
    <script>
      //构造函数
      var LineChart = function(ctx){
          // 获取绘图工具
          this.ctx = ctx || document.querySelector('canvas').getContext('2d');
          //画布的大小
          this.canvasWidth = this.ctx.canvas.width;
          this.canvasHeight = this.ctx.canvas.height;
          //网格的大小
          this.gridSize = 10;
          //坐标系的间距
          this.space = 20;
          //坐标原点
          this.x0 = this.space;
          this.y0 = this.canvasHeight-this.space;
          //坐标系的箭头
          this.arrowSize = 10;
          //绘制点
          this.dottedSize = 6;
          //点的坐标和数据有关系,数据可视化
      }
      //行为方法
      LineChart.prototype.init =function(data) {
         this.drawGrid();
         this.drawAxis();
         this.drawDotted(data);
      };//初始化行为
      LineChart.prototype.drawGrid =function() {
         //x轴方向的线
         var xLineTotal = Math.floor(this.canvasHeight/this.gridSize)
         for(var i= 0;i<=xLineTotal;i++){
            this.ctx.beginPath();
            this.ctx.moveTo(0,i*this.gridSize-0.5)
            this.ctx.lineTo(this.canvasWidth,i*this.gridSize-0.5)
            this.ctx.strokeStyle ='red';
            this.ctx.stroke()
         }
         //y轴方向的线
         var yLineTotal = Math.floor(this.canvasWidth/this.gridSize);
         for(var i =0; i<=yLineTotal;i++){
            this.ctx.beginPath();
            this.ctx.moveTo(i*this.gridSize-0.5,0)
            this.ctx.lineTo(i*this.gridSize-0.5,this.canvasHeight);
            this.ctx.strokeStyle ='red';
            this.ctx.stroke()
         }
      }; //绘制网格
      LineChart.prototype.drawAxis =function() {
         //x轴
           this.ctx.beginPath();
           this.ctx.strokeStyle ='green';
           this.ctx.moveTo(this.x0,this.y0);
           this.ctx.lineTo(this.canvasWidth-this.space,this.y0)
           this.ctx.lineTo(this.canvasWidth-this.space-this.arrowSize,this.y0+this.arrowSize/2)
           this.ctx.lineTo(this.canvasWidth-this.space-this.arrowSize,this.y0-this.arrowSize/2)
           this.ctx.lineTo(this.canvasWidth-this.space,this.y0)
           this.ctx.fill();
           this.ctx.stroke();
         //y轴
         this.ctx.beginPath();
         this.ctx.strokeStyle ='green';
         this.ctx.moveTo(this.x0,this.y0)
         this.ctx.lineTo(this.x0,this.space)
         this.ctx.lineTo(this.space+this.arrowSize/2,this.space+this.arrowSize)
         this.ctx.lineTo(this.space-this.arrowSize/2,this.space+this.arrowSize)
         this.ctx.lineTo(this.space,this.space)
         this.ctx.fill()
         this.ctx.stroke()
      } ;//绘制坐标系
      LineChart.prototype.drawDotted =function(data) {
         //数据的坐标需要转换成canvas坐标,再进行点的绘制,在连线
         //x=原点的坐标+数据的坐标
         //y=原点的坐标-数据的坐标
         var that = this;
         //记录当前坐标
         var prevCanvasX = 0;
         var prevCanvasY = 0;
         data.map((item,i)=>{
             var canvasX = that.x0+item.x;
             var canvasY = that.y0-item.y;
            console.log(canvasX-that.dottedSize/2,canvasY-that.dottedSize/2)
            //绘制点
            that.ctx.beginPath();
            that.ctx.moveTo(canvasX-that.dottedSize/2,canvasY-that.dottedSize/2);
            that.ctx.lineTo(canvasX+that.dottedSize/2,canvasY-that.dottedSize/2);
            that.ctx.lineTo(canvasX+that.dottedSize/2,canvasY+that.dottedSize/2);
            that.ctx.lineTo(canvasX-that.dottedSize/2,canvasY+that.dottedSize/2);
            that.ctx.closePath();
            that.ctx.fill();
            //点的连线
            //当是第一点时,起点是x0,y0
            //当不是第一点时,起点是上一个点
            if(i==0){
              that.ctx.beginPath();
              that.ctx.moveTo(that.x0,that.y0)
              that.ctx.lineTo(canvasX,canvasY)
              that.ctx.stroke();
            }else{
               that.ctx.beginPath();
               that.ctx.moveTo(prevCanvasX,prevCanvasY) 
               that.ctx.lineTo(canvasX,canvasY)  
               that.ctx.stroke();
            }
            //每次记录最新的点
            prevCanvasX = canvasX;
            prevCanvasY = canvasY;
         })
      } ;//绘制所有的点
      //初始化,数据应该是从后端获取的
      var data = [
        {
          x:100,
          y:120
        },
        {
          x:200,
          y:160
        },
        {
          x:300,
          y:240
        },
        {
          x:400,
          y:320
        },
        {
          x:500,
          y:80
        },
      ];
      var LineChart=  new LineChart();
      LineChart.init(data);
    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想在 PyQt5 中绘制折线图(line chart),可以使用 Matplotlib 库。下面是一个简单的示例代码: ```python import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QVBoxLayout, QWidget from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure class MainWindow(QMainWindow): def __init__(self): super().__init__() # 创建 Matplotlib 形 self.figure = Figure(figsize=(5, 4), dpi=100) self.canvas = FigureCanvas(self.figure) self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # 创建一个垂直布局,并将 Matplotlib 形添加到其中 layout = QVBoxLayout() layout.addWidget(self.canvas) # 创建一个 QWidget,用于放置布局 widget = QWidget() widget.setLayout(layout) self.setCentralWidget(widget) # 绘制折线图 self.plot() def plot(self): # 获取 Matplotlib 的 Axes 对象 ax = self.figure.add_subplot(111) # 准备数据 x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] # 绘制折线图 ax.plot(x, y) # 添加标题和坐标轴标签 ax.set_title("Line Chart") ax.set_xlabel("X-axis") ax.set_ylabel("Y-axis") # 更新 Matplotlib 形 self.canvas.draw() if __name__ == "__main__": app = QApplication(sys.argv) mainWindow = MainWindow() mainWindow.show() sys.exit(app.exec_()) ``` 在这个示例中,我们首先创建了一个 Matplotlib 形,并将其添加到一个垂直布局中。然后,我们定义了一个 `plot` 方法,用于绘制折线图。在 `plot` 方法中,我们获取了 Matplotlib 的 Axes 对象,并使用 `plot` 函数绘制折线图。最后,我们添加了标题和坐标轴标签,并更新了 Matplotlib 形。 在 `__main__` 方法中,我们创建了一个 QApplication 对象,并将其传递给我们的 MainWindow 类。然后,我们显示了窗口并启动了应用程序的事件循环。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值