klinecharts / KLineChart

📈Lightweight k-line chart that can be highly customized. Zero dependencies. Support mobile.(可高度自定义的轻量级k线图,无第三方依赖,支持移动端)
https://klinecharts.com/
Apache License 2.0
2.38k stars 598 forks source link

[Feature] 能否提供一下相关源代码?非常感谢 #328

Closed btdan closed 1 year ago

btdan commented 1 year ago

需求描述

https://klinecharts.com/zh-CN/sample 这个页面展示的很丰富,能否帮忙提供一下源代码?非常感谢

具体实现

https://klinecharts.com/zh-CN/sample

guotie commented 1 year ago

+1

Athson commented 1 year ago

+1,那个标记功能是什么?createTag? createAnnotation?

OPQAI commented 1 year ago
试试这个(try this):

我从https://klinecharts.com/zh-CN/sample页面源码中找到的:
(I found it in the page source code: https://klinecharts.com/zh-CN/sample)

// 标记点
 const markerList = [
      {
        point: { timestamp: 1671552000000, value: 3.05 },
        styles: {
          position: 'point',
          offset: [2, 0],
          symbol: {
            type: 'custom',
          },
        },
        drawExtend(params) {
          const { ctx, coordinate } = params;
          annotationDrawExtend(ctx, coordinate, '哈哈哈');
        },
      },
    ];

    console.log('markerList: ', markerList);

     /** 图形的实例instance */
     const chart: klinecharts.Chart = chartRef.current;
// 绘制标记
 chart.createAnnotation(markerList);

/** 绘制标记的函数 */
function annotationDrawExtend(
  ctx: CanvasRenderingContext2D,
  /** 坐标点 */
  coordinate: { x: number; y: number },
  /** 要绘制的文本 */
  text: string,
) {
  const color = '#2d6187';
  ctx.font = '12px Roboto';
  // 矩形边框的背景色
  ctx.fillStyle = color;
  ctx.strokeStyle = color;

  const textWidth = ctx.measureText(text).width;
  const startX = coordinate.x;
  let startY = coordinate.y - 6;

  // 接下来画一条竖线
  ctx.setLineDash([3, 3]);
  ctx.beginPath();
  /** 线的高度 */
  const LINE_HEGITH = 50;
  // 从某根k线柱子的顶端往上画一条虚线
  ctx.moveTo(startX, startY);
  ctx.lineTo(startX, startY - LINE_HEGITH);
  ctx.closePath();
  ctx.stroke();

  /** 绘制一个三角形的箭头 */
  startY -= 50;
  ctx.beginPath();
  ctx.moveTo(startX, startY);
  ctx.lineTo(startX - 4, startY - 5);
  ctx.lineTo(startX + 4, startY - 5);
  ctx.closePath();
  ctx.fill();

  // 绘制一个矩形边框
  const rectX = startX - textWidth / 2 - 6;
  const rectY = startY - 5 - 28;
  const rectWidth = textWidth + 12;
  const rectHeight = 28;
  /** 矩形的圆角 */
  const radius = 2;
  ctx.beginPath();
  ctx.moveTo(rectX + radius, rectY);
  ctx.arcTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + rectHeight, radius);
  ctx.arcTo(rectX + rectWidth, rectY + rectHeight, rectX, rectY + rectHeight, radius);
  ctx.arcTo(rectX, rectY + rectHeight, rectX, rectY, radius);
  ctx.arcTo(rectX, rectY, rectX + rectWidth, rectY, radius);
  ctx.closePath();
  ctx.fill();

  // 绘制文本
  // 文本颜色是白色
  ctx.fillStyle = '#fff';
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'center';
  ctx.fillText(text, startX, startY - 5 - 14);
}

+1,那个标记功能是什么?createTag? createAnnotation?