Saturday, April 27, 2013

Water mark plugin for flot

recently i needed to add some marker to all graphs in my project, since many people are using our tool and taking print-screen of the graphs for mail chain, without giving any credit :P.
so we decided to add marker text to all graphs, I found there is no straight forward way or plug-in available to add water mark or text to flot graphs. then I explored the flot API, found its well designed and easy to add plug-ins.
i created jquery.flot.marker.js
(function ($) {
    var options = {
        marker: {
            mode: null, // thinking to use for image based , text base markers
            value: "My Graph", // default value
            color: "rgba(100, 100, 100, 0.80)",
            font: "14px Arial",
            position: 'top-right' //top-left, bottom-right, bottom-left
        }
    };
    function init(plot) {
        plot.hooks.draw.push(function (plot, ctx) {
            var c = plot.getOptions().marker;
            if (!c.mode)
                return;
            //alert(plot.offset().left);
            ctx.save();
            ctx.font=c.font;
            var w;
            var h;
            if((c.position=='top-right') || (c.position=='bottom-right')) {
                w = plot.getPlaceholder().width()*0.88;
            } else {
                w = plot.offset().left-40;
            }
            if((c.position=='top-left') || (c.position=='top-right')) {
                h = 45;
            } else {
                h = plot.height();
            }
            //alert(h);
            ctx.fillStyle=c.color;
            ctx.fillText(c.value, w, h);

        });
    }
    $.plot.plugins.push({
        init: init,
        options: options,
        name: marker,
        version: '1.0'
    });
})(jQuery);
Then including plug-in file helped me to get marker on all graphs.
<script language="javascript" type="text/javascript" src="../jquery.flot.marker.js"></script>
  plot = $.plot($("#placeholder"), 
                      ${data}, 
                          marker: {
                                mode: "text",
                                value:"My Graph",
                                color:"rgba(100, 100, 100, 0.60)",
                                font: "10px Lucida Sans Unicode",
                                position: 'top-right'                           
                            },

                            grid: { hoverable: true, autoHighlight: false },
                            yaxis: { min: -1.2, max: 1.2 }
                        });

No comments:

Post a Comment

Search Ranjeet's Blog