function draw(data) { let canvas = document.getElementById('stock-canvas'), width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, width, height); let NUMS = 30; let max = data.reduce((x, y) => (x.high > y.high) ? x : y).high;//3684.57 let min = data.reduce((x, y) => (x.low < y.low) ? x : y).low;//3327.81 let padding = 2; //内边距 let dw = 4;//宽 let dh = height - padding * 2;//高 let space = (width - padding * 2 - dw * NUMS) / (NUMS - 1); ctx.font = '12px Arial'; console.log(max, min, dw, dh, space); function getY(y) { return padding + (max - y) * dh / (max - min); } for (let i = 0; i < data.length; i++) { let d = data[i]; let x = padding + dw / 2 + (dw + space) * i; //背景 ctx.fillStyle = '#eee'; ctx.fillRect(x - dw / 2, padding, dw, dh); //垂直线 ctx.beginPath(); ctx.moveTo(x, getY(d.high)); ctx.lineTo(x, getY(d.low)); ctx.stroke(); //K线 ctx.fillStyle = d.open > d.close ? 'green' : 'red'; ctx.fillRect(x - dw / 2, getY(d.open), dw, (d.open - d.close) * dh / (max - min)); } //最高值和最低值 ctx.fillStyle = '#333'; ctx.fillText(max, padding, padding + 8); ctx.fillText(min, padding, height - padding); }
Sign in to make a reply
jinglepper