使用canvas绘制K线图
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>mysite</title>
<link rel="stylesheet" href="my.css">
<style>
#canvas {
border: 1px solid gray;
}
</style>
</head>
<body>
<canvas id="canvas" width="500px" height="500px">
</canvas>
<p id="info"></p>
<script>
'use strict';
var NUM = 30;
function drawStock(arr) {
var total_low = 3000;
var total_high = 5000;
var padding = 10;
var gap = 6;
var line_width = 2;
var canvas = document.getElementById("canvas");
var width = canvas.width;
var height = canvas.height;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "#faf6fc";
ctx.fillRect(0, 0, 500, 500);
ctx.strokeRect(10, 10, 480, 480);
var point_height = (width - padding * 2) / (total_high - total_low);
var box_width = ((width - padding * 2) - gap * (NUM + 1)) / NUM;
for (let i = 1; i < arr.length + 1; i++) {
var pad_x = padding + i * gap + (i - 1) * box_width;
var t = i - 1;
drawK(pad_x, arr[t].open, arr[t].close, arr[t].high, arr[t].low);
}
function drawK(pad_x, open, close, high, low) {
var box_height_point = Math.abs(open - close);
var box_height = box_height_point * point_height;
var pad_y = height - (Math.max(open, close) - total_low) * point_height - gap;
ctx.fillStyle = (open > close) ? "green" : "red";
box_height = Math.max(box_height, 2);
ctx.fillRect(pad_x, pad_y, box_width, box_height);
pad_x = pad_x + box_width / 2 - line_width / 2;
pad_y = height - (high - total_low) * point_height - gap;
box_height = (high - low) * point_height;
ctx.fillRect(pad_x, pad_y, line_width, box_height);
}
}
function loadStockData(r) {
var offset = 50;
var data = r["data"];
if (data.length > NUM) {
data = data.slice(offset, offset + NUM);
}
data = data.map(function(x) {
return {
data: x[0],
open: x[1],
close: x[2],
high: x[3],
low: x[4],
vol: x[5],
change: x[6]
}
});
drawStock(data);
}
var js = document.createElement("script");
js.src = "http://img1.money.126.net/data/hs/kline/day/history/2015/0000001.json?callback=loadStockData&t=" + Date.now();
document.getElementsByTagName("head")[0].appendChild(js);
</script>
</body>
</html>