参考评论区改出的一种实现
var // 获取输出区域 canvas = document.getElementById('stock-canvas'), width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d') console.log(JSON.stringify(data[0])) // {"date":"20150602","open":4844.7,"close":4910.53,"high":4911.57,"low":4797.55,"vol":62374809900,"change":1.69} ctx.clearRect(0, 0, width, height) var // 获取最高价和最低价 max = data.map(x => x.high).reduce((x, y) => x > y ? x : y), // 最高价 min = data.map(x => x.low).reduce((x, y) => x < y ? x : y) // 最低价 var // 计算图像宽高 unitLen = Math.min(1, canvas.height / (max - min)), // 单位价格区间长度对应的坐标长度 bottom = (max - min) * unitLen, // 图像高度(图像最低点) spacing = Math.min(15, canvas.width / 30), // 中心线间隔 unitWidth = spacing / 1.5, // 矩形宽 start = spacing / 2 // 中心线起始位置 for (let foo = 0; foo < data.length; foo++) { let coord = start + spacing * foo // 中心线横坐标 // 绘制中心线 var path = new Path2D() path.moveTo(coord, bottom - (data[foo].low - min) * unitLen) path.lineTo(coord, bottom - (data[foo].high - min) * unitLen) ctx.strokeStyle = 'black' ctx.stroke(path) // 绘制矩形 let higher, lower if (data[foo].open < data[foo].close) { ctx.fillStyle = 'red' higher = data[foo].close lower = data[foo].open } else { ctx.fillStyle = 'green' higher = data[foo].open lower = data[foo].close } ctx.fillRect( // 起点:(coord - unitWidth / 2, bottom - (higher - min) * unitLen) coord - unitWidth / 2, bottom - (higher - min) * unitLen, // 大小:unitWidth x (higher - lower) * unitLen unitWidth, (higher - lower) * unitLen ) }
Sign in to make a reply
忒修斯之船
参考评论区改出的一种实现