画布绘制扭曲的图形和文本

时间:2015-01-20 15:48:26

标签: javascript html5 canvas html5-canvas

我正在使用Canvas构建一个简单的图表。 (那里的所有自定义包都不符合我的需要)。

在最基本的发展阶段,我已经陷入了我试图绘制的一切扭曲效果。我一直潜伏在论坛上寻找答案,我没有将CSS规则应用于canvas标签。

HTML:

 <div id="platform-wrapper">
     <canvas id="platform-chart" width="500" height="250"></canvas>
 </div>

CSS:

#platform-wrapper {
    width: 500px;
    height: 250px;
}

JS:

;(function() {
var PlatformChart = function() {
    var graph,
        canvas,
        ctx,
        xPadding = 30,
        yPadding = 30,
        data = { values:[
            { X: "16:13:15", Y: 1.23453 },
            { X: "16:13:30", Y: 1.24528 },
            { X: "16:13:45", Y: 1.23438 },
            { X: "16:14:00", Y: 1.34544 },
            { X: "16:14:15", Y: 1.53444 }
        ]};

    function getMaxY() {
        var max = 0;

        for(var i = 0; i < data.values.length; i ++) {
            if(data.values[i].Y > max) {
                max = data.values[i].Y;
            }
        }

        return max;
    }

    function getXPixel(val) {
        return ((graph.width() - xPadding) / data.values.length) * val + (xPadding * 1.5);
    }

    function getYPixel(val) {
        return graph.height() - (((graph.height() - yPadding) / getMaxY()) * val) - yPadding;
    }

    return {
        init: function(canvasId) {
            var selector = '#'+canvasId;

            if (!canvasId || !$(selector).length) return false;

            graph = $(selector);
            canvas = graph[0];
            ctx = canvas.getContext('2d');

            return this;
        },

        config: function(config) {
            for(var prop in config) {
                if (ctx.hasOwnProperty(prop)) {
                    ctx[prop] = config[prop];
                }
            }

            return this;
        },

        drawBase: function() {
            //ctx.rect(0, 0, canvas.width, canvas.height);
            //ctx.fillStyle = "#4c88e1";
            //ctx.fill();
            return this;
        },

        clear: function() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            return this;
        },

        drawX: function(offset) {
            //ctx.fillStyle = "#fff";

            for(var i = 0; i < data.values.length; i ++) {
                ctx.fillText(data.values[i].X, getXPixel(i) + xPadding - 20, graph.height() - 10);
            }

            return this;
        },

        drawY: function(offset) {
            ctx.textAlign = "right";
            //ctx.textBaseline = "middle";
            //ctx.fillStyle = "#fff";

            for(var i = 0; i < data.values.length; i ++) {
                ctx.fillText(data.values[i].Y, graph.width() - 10, getYPixel(i) - yPadding);
            }

            return this;
        }
    }
};

    window.platformChart = new PlatformChart();
}());

通过控制台初始化:

platformChart.init('platform-chart').config({lineWidth:2, strokeStyle:'#333', textAlign: 'center'}).drawBase().drawX().drawY()

JSFiddle

0 个答案:

没有答案