Highcharts Demo

author(s): Torstein Hønsi

by Amanda Williamson

HTML

<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="container" style="height: 600px; width:600px;"></div>

CSS

#container {
    border:1px solid;
}

.annotation { 
    transition: opacity 0.3s;
    border: 2px solid red;
}

JavaScript

$(function () {
    // the renderer
    var renderer = new Highcharts.Renderer($('#container')[0], 600, 600),
        
        // rect
        // however, you can use any method that highcharts does
        // arc, circle, image, path, rect, text
        r,
        
        // boolean to check whether the mouse is down
        isDown = false,
        
        // x anchor (the x point where the mouse was initially clicked)
        anchorX,
        
        // y anchor (the y point where the mouse was initially clicked
        anchorY;

    
    // event handler for mousedown event
    $('#container').mousedown(function (e) {
        isDown = !isDown;
        anchorX = e.pageX;
        anchorY = e.pageY;
        
        r = renderer.rect(anchorX, anchorY, 0, 0, 5)
            .attr({
            'stroke-width': 2,
            stroke: 'blue',
            fill: 'lightblue',
            zIndex: 3,
                class: 'annotation'                                
        }).add()
    });    

    // event handler for mousemove event
    $('#container').mousemove(function (e) {

        if (isDown) {
            var x = r.attr('x'),
                y = r.attr('y'),
                w = r.attr('width'),
                h = r.attr('height'),
                newX,
                newY,
                newWidth,
                newHeight;
            
            newWidth = e.clientX - anchorX;
            newHeight = e.clientY - anchorY;
           
            // width & height cannot be negative so change x if negative
            r.attr({
                x: newWidth < 0 ? e.clientX : anchorX,
                y: newHeight < 0 ? e.clientY : anchorY,
                width: newWidth < 0 ? Math.abs(newWidth) : newWidth,
                height: newHeight < 0 ? Math.abs(newHeight) : newHeight
            }).add();
        }

    });


});