在EXTJS折线图中创建自定义线

时间:2012-12-28 11:56:36

标签: javascript extjs

我需要在Line图表上添加一条垂直线和一个文本,靠近图表上的指定点(由数据指定,而不是坐标)。我尝试使用CompositeSprites,但它并没有完全显示在屏幕上。我是ExtJS绘画的新手。

1 个答案:

答案 0 :(得分:1)

您应该在图表的refresh事件监听器中添加垂直线的逻辑,这样,如果数据发生更改,行位置将更新以反映新数据。

这是一个如何做到这一点的例子,假设你可以获得对图表容器的引用(例如“myPanel”):

var myChart = myPanel.down('chart'),

myChart.on('refresh', function(myChart) {

    // First, get a reference to the record that you want to position your 
    // vertical line at. I used a "findRecord" call below but you can use 
    // any of the datastore query methods to locate the record based on 
    // some logic: findBy (returns index #), getAt, getById, query, queryBy
    var myRecord = myChart.store.findRecord(/*[someField]*/, /*[someValue]*/),

    // a reference to the series (line) on the chart that shows the record
    mySeries = myChart.series.first(), 

    // get the chart point that represents the data
    myPoint = Ext.each(mySeries.items, function(point) {
        return myRecord.id === point.storeItem.id;
    }),

    // the horizontal position of the point
    xCoord = point.point[0],

    // check for any previously drawn vertical line
    myLine = myChart.surface.items.findBy(function(item) {
        item.id === 'vert'
    });

    // if there is no previously drawn line add it to the "surface"
    if (!myLine) {

        myChart.surface.add({
            id: 'vert', // an id so that we can find it again later
            type: 'rect',
            width: 4,
            height: myChart.surface.height, // the same height as the chart
            fill: 'black',
            opacity: 0.5, // some transparency might be good
            x: xCoord,
            y: 0 // start the line at the top of the chart
        });

    // if we already had a line just reposition it's x coordinate            
    } else {

        myLine.setAttributes({
            translate: {
                x: xCoord,
                y: 0
            }

        // I think the chart gets drawn right after the refresh event so 
        // this can be false, I haven't tested it though
        }, false);

    }
});

如果您使用的是MVC模式,您的事件处理程序会有所不同(您不会使用myChart.on())。