美文网首页
canvas的客户端与服务端绘图

canvas的客户端与服务端绘图

作者: 然后呢_ | 来源:发表于2019-06-28 10:34 被阅读0次

echarts的两种渲染

  1. npm install echarts
    客户端渲染 —— ECharts是一个使用 JavaScript 实现的开源可视化库。基于 html5 的 canvas 绘图实现。
    实现效果如下:
    canvas客户端渲染.png

因平时项目使用多,故不做详细描述

  1. npm install node-echarts
    服务端渲染 —— 最终生成一张指定图片返回

新建 demo/index.js 文件

var node_echarts = require('node-echarts');
node_echarts({
  width: 500, // Image width, type is number.
  height: 500, // Image height, type is number.
  option: {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [820, 932, 901, 934, 1290, 1330, 1320],
      type: 'line'
    }]
  }, // Echarts configuration, type is Object.
  //If the path  is not set, return the Buffer of image.
  path: __dirname + '/demo.png', // Path is filepath of the image which will be created.
  enableAutoDispose: true //Enable auto-dispose echarts after the image is created.
})

终端进入demo文件夹执行 node index.js 后查看 demo 文件夹生成一张命名为 demo 的png图片

node_echarts 生成图片.png

原生canvas

使用canvas绘制线条

ctx.beginPath();
ctx.moveTo(125,125);
ctx.lineTo(125,45);
ctx.lineTo(45,125);
ctx.closePath();
ctx.stroke(); // 实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径, 画出当前路径的边框

如何使用 canvas 绘制以下图形


canvas 绘制图像.png
function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext){
  var ctx = canvas.getContext('2d');
    
    
  var option = {
    TimeLine: ['0min 开始构建', '10min 开始测试', '15min 结束'],
    xAxis: ['0min', '20min', '30min'], // x轴数据
    yAxis: [10, 16, 15], // y轴数据
    // height: 400, // 图片高度(默认500)
    // width: 400, // 图片宽度 (默认500)
  }
    
    
  // 绘制时间轴
  var TimeLine = option.TimeLine
  TimeLine.map((item, index) => {
    ctx.fillText(item, 20, 20*(index+1))
  })
    
  
  // 绘制折线图
  var chartTop = 20*(TimeLine.length+1) // 图表顶部起始高度
  var chartLeft = 20 // 图表左侧起始宽度
  var canvasBottom = option.height || 500 // canvas整体高度
  var canvasRight = option.width || 500 // canvas整体宽度
    
   // 绘制边框线
  ctx.beginPath();
  ctx.moveTo(chartLeft,chartTop);
  ctx.lineTo(chartLeft,canvasBottom);
  ctx.lineTo(canvasRight,canvasBottom);
  ctx.stroke();
  
  
  var chartWidth = canvasRight - 20 // 图表x轴实际宽度
  var chartHeight = canvasBottom - chartTop // 图表y轴实际高度
 
  // 坐标轴原始数据
  var x = option.xAxis
  var y = option.yAxis
  // 坐标轴渲染数据
  var xAxis = []
  var yAxis = []
  var offset = 20 // label偏移量
 
    
  // 绘制x轴
  var xSection = chartWidth/x.length
  var xOffset = xSection / 2 // 中心点偏移量
  x.map((item, index) => {
    ctx.fillText(item, xSection * (index+1) - xOffset, canvasBottom + offset)
    xAxis.push(xSection * (index+1) - xOffset)
  })
    
  // 绘制y轴
  var max = Math.max(...y) // y轴最大值
  var interval = 5 // 自定义y轴间隔
  
  /**
  * 原代码
  * var sectionNum = max / interval // y轴切割份数
  * 若interval=5, max=16时,max应该为20
  * 所以 切割份数必须向上取整,然后再根据切割份数重新定义y轴最大值
  */
  var sectionNum = Math.ceil(max / interval) // y轴切割份数
  max = interval * sectionNum // 根据切割份数重新定义最大值
  
    
  var ySection = chartHeight / sectionNum // y轴每个间隔区域的高度
  var yOffset = ySection / 2 // 中心点偏移量
 
  for (var i=0;i<sectionNum;i++) {
    var itemy = canvasBottom - ySection * (i + 1) // y轴分割线y坐标
    ctx.fillText( interval * (i+1), chartLeft - offset, itemy)
    yAxis.push(canvasBottom - chartHeight/max*(y[i]))
    
    // 绘制y轴间隔线
    ctx.beginPath();
    ctx.moveTo(chartLeft, itemy);
    ctx.lineTo(canvasRight, itemy);
    ctx.strokeStyle = "#eee";//线条的颜色
    ctx.stroke();
  }
  
  // 绘制图表坐标点
  ctx.beginPath();
  xAxis.map((item, index) => {
    ctx.lineTo(item,yAxis[index])
    ctx.strokeStyle = "#dc4e4e";//线条的颜色
  })
  ctx.stroke();  
  }
}

实际运行效果

node-canvas

  1. brew install pkg-config cairo pango libpng jpeg giflib
    此时执行 npm install canvas 安装失败
    安装失败.png
  1. 执行 brew install libffi 然后分别按照提示执行以下步骤
    brew reinstall libffi
    export PKG_CONFIG_PATH="/usr/local/opt/libffi/lib/pkgconfig"
    安装环境成功.png
  1. npm install canvas 安装成功

  2. 新建 demo/canvas.js 文件

const { createCanvas, loadImage } = require('canvas')
var fs = require('fs')
var resolve = require('path').resolve


const canvas = createCanvas(200, 200)
const ctx = canvas.getContext('2d')

// Write "Awesome!"
ctx.font = '30px Impact'
ctx.rotate(0.1)
ctx.fillText('Awesome!', 50, 100)

// Draw line under text
var text = ctx.measureText('Awesome!')
ctx.strokeStyle = 'rgba(0,0,0,0.5)'
ctx.beginPath()
ctx.lineTo(50, 102)
ctx.lineTo(50 + text.width, 102)
ctx.stroke()


var outPath = resolve(__dirname, 'rectangle.png')
canvas.createPNGStream().pipe(fs.createWriteStream(outPath))
  1. 终端执行 node canvas.js 成功生成图片
    node_canvas 生成图片.png

具体使用方式参考https://github.com/Automattic/node-canvas
或demo示例https://github.com/Automattic/node-canvas/tree/master/examples

相关文章

网友评论

      本文标题:canvas的客户端与服务端绘图

      本文链接:https://www.haomeiwen.com/subject/flxscctx.html