Discuss / JavaScript / 交作业

交作业

Topic source
var
  canvas = document.getElementById('stock-canvas'),
  width = canvas.width,
  height = canvas.height,
  ctx = canvas.getContext('2d');
console.log(JSON.stringify(data));
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = 'black';
ctx.fillText('Test Canvas', 10, 10);

// 价格基准点
var base_price = data[0].open;
// 整K的y轴基准位置
var base_y = 100;
// k线图缩小比例
var scale = 4;
// 日K的宽度/2
var single_width_half = 3;
// 日K的宽度
var single_width_solo = single_width_half * 2;
// 日K的间隔
var single_margin = 2;
// 日K加间隔的宽度
var single_width = single_width_solo + single_margin;

for (var i in data) {
  // 收盘大于开盘,涨!红色。
  // 收盘小于开盘,跌!绿色。
  // 收盘等于开盘,横盘!灰色。
  if (data[i].close > data[i].open) {
    ctx.fillStyle = 'red';
    ctx.strokeStyle = 'red';
  } else if (data[i].close < data[i].open) {
    ctx.fillStyle = 'green';
    ctx.strokeStyle = 'green';
  } else {
    ctx.fillStyle = 'grey';
    ctx.strokeStyle = 'grey';
  }
  // 开/收高点
  var open_close_high = data[i].open > data[i].close ? data[i].open : data[i].close;
  // 开/收低点
  var open_close_low = data[i].open < data[i].close ? data[i].open : data[i].close;

  // 画开收矩形,开/收作为矩形的上下点
  var rect_start = base_y - (open_close_high - base_price) / scale;
  var rect_height = (Math.abs(data[i].open - data[i].close)) / scale;
  ctx.fillRect(20 + single_width * i, rect_start, single_width_solo, rect_height);

  // 画高直线,当高点大于开收高点,才会有高直线
  if (data[i].high > open_close_high) {
    var high_line_start = base_y - (data[i].high - base_price) / scale;
    var high_line_end = base_y - (open_close_high - base_price) / scale;
    ctx.beginPath();
    ctx.moveTo(20 + single_width_half + single_width * i, high_line_start);
    ctx.lineTo(20 + single_width_half + single_width * i, high_line_end);
    ctx.stroke();
  }

  // 画低直线,当低点大于开收低点,才会有低直线
  if(data[i].low < open_close_low) {
    var low_line_start = base_y - (open_close_high - base_price) / scale;
    var low_line_end = base_y - (data[i].low - base_price) / scale;
    ctx.beginPath();
    ctx.moveTo(20 + single_width_half + single_width * i, low_line_start);
    ctx.lineTo(20 + single_width_half + single_width * i, low_line_end);
    ctx.stroke();
  }
}

  • 1

Reply