练习

    请根据从163获取的JSON数据绘制最近30个交易日的K线图,数据已处理为包含一组对象的数组:

    window.drawStock = function (data) {

    var

    canvas = document.getElementById('stock-canvas'),

    MAX_X = canvas.width,

    MAX_Y = canvas.height,

    ctx = canvas.getContext('2d');



    var low = data.reduce(function (prev, x) {

    return x.low < prev.low ? x : prev;

    });

    var high = data.reduce(function (prev, x) {

    return x.high > prev.high ? x : prev;

    });



    var chg = high.high - low.low;



    // index range:

    var lowest = Math.floor(low.low - chg 0.1);

    var highest = Math.floor(high.high + chg
    0.1 + 1);



    var calcY = function (idx) {

    return MAX_Y (highest - idx) / (highest - lowest);

    };



    var drawAtX = function (x, k) {

    var

    tmp,

    y1 = calcY(k.open),

    y2 = calcY(k.close);

    if (y1 > y2) {

    tmp = y1;

    y1 = y2;

    y2 = tmp;

    }

    ctx.fillStyle = (k.open > k.close) ? '#00ff00' : '#ff0000';

    ctx.fillRect(x, calcY(k.high), 1, calcY(k.low) - calcY(k.high));

    ctx.fillRect(x-2, y1, 5, y2 - y1);

    };



    ctx.clearRect(0, 0, MAX_X, MAX_Y);



    ctx.font = '12px serif';

    ctx.textAlign = 'right';

    ctx.fillStyle = '#000000';

    ctx.fillText(String(Math.floor(high.high)), 40, 15);

    ctx.fillText(String(Math.floor(low.low)), 40, MAX_Y - 20);



    var i, x;

    for (i=0; i<data.length; i++) {

    x = i
    8 + 50;

    drawAtX(x, data[i]);

    }

    };

    'use strict';



    window.loadStockData = function (r) {

    var

    NUMS = 30,

    data = r.data;

    if (data.length > NUMS) {

    data = data.slice(data.length - NUMS);

    }

    data = data.map(function (x) {

    return {

    date: x[0],

    open: x[1],

    close: x[2],

    high: x[3],

    low: x[4],

    vol: x[5],

    change: x[6]

    };

    });

    window.drawStock(data);

    }



    window.drawStock = function (data) {



    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);

    ctx.fillText('Test Canvas', 10, 10);



    };



    // 加载最近30个交易日的K线图数据:

    var js = document.createElement('script');

    js.src = 'http://img1.money.126.net/data/hs/kline/day/history/2015/0000001.json?callback=loadStockData&t=&#39; + Date.now();

    document.getElementsByTagName('head')[0].appendChild(js);

    下载为图片