使用jquery 简单自制条形图 示例

本文介绍如何使用HTML5 Canvas和JavaScript实现一个动态时间轴,包括绘制坐标轴、添加刻度线及辅助线等功能,并通过具体示例展示了如何将特定的日期和时间映射到坐标轴上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >




源码:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
    <style type="text/css">
    .hArrow
    {
        width:20px;
        height:20px;
        background-color:Red;
        }
        .vArrow
    {
        width:20px;
        height:20px;
        background-color:Lime;
        }
    </style>
</head>
<body>
    <div id="testContainer" style="width:1200px; height:600px; margin-top:200px; margin-left:100px; background-color:#CAF0FF; overflow:auto;"></div>
    <!-- 全局变量 -->
    <script type="text/javascript">
        window["linesTotalCount"] = 0;
        window["原点偏移量x"] = 120;
        window["原点偏移量y"] = 40;
        window["坐标余量"] = 30;
        window["显示速度"] = 1200;
        window["线条宽度"] = 30;
        window["辅助线颜色"] = "#99CCFF";
    </script>
    <!-- 画坐标轴 -->
    <script type="text/javascript">
        function drawCoordinates(direction, tipArray, showSubLine, showSubLineColor, containerID, scaleLength, originalPoint, bgColor) {
            var coordinatesArray = new Array();
            if (direction != "h" && direction != "H" && direction != "v" && direction != "V") {
                return;
            }

            if (tipArray.length == 0) {
                return;
            }

            if(scaleLength == null)
            {
                scaleLength=10;
            }

            if (containerID == null) {
                containerID = "testContainer";
            }
            var container = jQuery("#" + containerID);

            if (originalPoint == null) {
                originalPoint = getOriginalPoint(containerID);
            }

            if (direction == "h" || direction == "H") {
                var containerWidth = container.width();
                var lineLength = containerWidth - window["原点偏移量x"] - window["坐标余量"];
                
                var startPoint = {};
                var endPoint = {};
                
                //画横轴线上的刻度;
                var eachScaleWidth = lineLength / tipArray.length;
                var startPoint = {};
                var endPoint = {};
                for (var i = 0; i < tipArray.length; i++) {
                    startPoint["x"] = eachScaleWidth * i;
                    startPoint["y"] = -1*scaleLength;
                    endPoint["x"] = eachScaleWidth * i;
                    endPoint["y"] = 0;
                    drawLineSegment(startPoint, endPoint, 1, "v", "scale", bgColor, tipArray[i]);

                    //填充结果数组
                    var coordinateItem = {};
                    coordinateItem["coordinateText"] = tipArray[i];
                    coordinateItem["x"] = eachScaleWidth * i;
                    coordinateItem["y"] = 0;
                    coordinatesArray.push(coordinateItem);

                    //辅助线
                    if (showSubLine == "true") {
                        if (i == 0) {
                            continue;
                        }
                        startPoint["x"] = eachScaleWidth * i;
                        startPoint["y"] = 0;
                        endPoint["x"] = eachScaleWidth * i;
                        endPoint["y"] = container.height() - window["原点偏移量y"] - window["坐标余量"];
                        drawLineSegment(startPoint, endPoint, 1, "v", "scale", showSubLineColor);
                    }
                }
                //画横轴线
                startPoint["x"] = 0;
                startPoint["y"] = 0;
                endPoint["x"] = lineLength + window["坐标余量"] / 3 * 2;
                endPoint["y"] = 0;
                drawLineSegment(startPoint, endPoint, 1, "h", "axis", bgColor);
            }

            if (direction == "v" || direction == "V") {
                var containerHeight = container.height();
                var lineLength = containerHeight - window["原点偏移量y"] - window["坐标余量"];
                
                var startPoint = {};
                var endPoint = {};
                
                //画横轴线上的刻度;
                var eachScaleWidth = lineLength / tipArray.length;
                var startPoint = {};
                var endPoint = {};
                for (var i = 0; i <tipArray.length; i++) {
                    startPoint["x"] = 0;
                    startPoint["y"] = eachScaleWidth * i;
                    endPoint["x"] = -1 * scaleLength;
                    endPoint["y"] = eachScaleWidth * i;
                    drawLineSegment(startPoint, endPoint, 1, "h", "scale", bgColor, tipArray[i]);

                    //填充结果数组
                    var coordinateItem = {};
                    coordinateItem["coordinateText"] = tipArray[i];
                    coordinateItem["x"] = 0;
                    coordinateItem["y"] = eachScaleWidth * i;
                    coordinatesArray.push(coordinateItem);

                    //辅助线
                    if (showSubLine == "true") {
                        startPoint["x"] = 0;
                        startPoint["y"] = eachScaleWidth * i;
                        endPoint["x"] = container.width() - window["原点偏移量x"] - window["坐标余量"];
                        endPoint["y"] = eachScaleWidth * i;
                        drawLineSegment(startPoint, endPoint, 1, "h", "scale", showSubLineColor);
                    }
                }
                //画横轴线
                startPoint["x"] = 0;
                startPoint["y"] = 0;
                endPoint["x"] = 0;
                endPoint["y"] = lineLength + window["坐标余量"] / 3 * 2;
                drawLineSegment(startPoint, endPoint, 1, "v", "axis", bgColor);
            }

            return coordinatesArray;
        }
    </script>
    <!-- 画箭头 -->
    <script type="text/javascript">
        function drawArrow(direction, endPoint, containerID, originalPoint) {
            var html = '';
            if (direction == "h" || direction == "H") {
                var tempEndPoint = getAbsolutPosition(originalPoint, endPoint);
                var xPosition = tempEndPoint["x"] - 10;
                var yPosition = tempEndPoint["y"] - 10;
                html = "<div class=\"hArrow\" style=\"position:absolute;top:" + yPosition + "px;left:" + xPosition + "px;\"></div>"
            }
            if (direction == "v" || direction == "V") {
                var tempEndPoint = endPoint;
                var xPosition = tempEndPoint["x"] - 10;
                var yPosition = tempEndPoint["y"] - 10;
                html = "<div class=\"vArrow\" style=\"position:absolute;top:" + yPosition + "px;left:" + xPosition + "px;\"></div>"
            }
             var container = jQuery("#" + containerID);
             container.append(html);
        }
    </script>
    <!-- 画线段 -->
    <script type="text/javascript">
        function drawLineSegment(startPoint, endPoint, lineWidth, direction, type, bgColor, textToShow, originalPoint, containerID) {
            if (startPoint == null || startPoint["x"] == null || startPoint["y"] == null) {
                return;
            }
            if (endPoint == null || endPoint["x"] == null || endPoint["y"] == null) {
                return;
            }

            if (direction != "h" && direction != "H" && direction != "v" && direction != "V") {
                return;
            }

            if (type == null) {
                type = "normal";
            }
            if (type == "normal") {
                type = "normal";
            }
            else {
                if (type == "scale") {
                    type = "scale";
                }
                else if (type == "axis") {
                    type = "axis";
                }
                else {
                    type = "normal";
                }
            }

            if (lineWidth == null) {
                lineWidth == 10;
            }

            if (bgColor == null) {
                bgColor = "#000000";
            }

            if (containerID == null) {
                containerID = "testContainer";
            }
            var container = jQuery("#"+containerID);

            if (originalPoint == null) {
                originalPoint = getOriginalPoint(containerID);
            }

            if (container.length <= 0) {
                alert("Container is not existed !");
                return;
            }

            var htmlStr = "";

            var length = 0;
            if (direction == "h" || direction == "H") {
                length = endPoint["x"] - startPoint["x"];
                startPoint["y"] = startPoint["y"] - lineWidth / 2;

                if (length < 0) {
                    length = -1 * length;
                    startPoint["x"] = startPoint["x"] - length;
                }

                startPoint = getAbsolutPosition(originalPoint, startPoint);
                window["linesTotalCount"] = window["linesTotalCount"] + 1;
                if (type != "normal") {
                    htmlStr = "<div id=\"drawOutLine_" + window["linesTotalCount"] + "\" style=\"width:" + length + "px;height:" + lineWidth + "px; position:absolute; top:" + startPoint["y"] + "px; left:" + startPoint["x"] + "px; background-color:" + bgColor + "; line-height:" + lineWidth + ";\"></div>";
                    //添加箭头
                    if (type == "axis") {
                        drawArrow(direction, endPoint, containerID,originalPoint);
                    }
                }
                else {
                    //添加动画
                    htmlStr = "<div id=\"drawOutLine_" + window["linesTotalCount"] + "\" style=\"height:" + lineWidth + "px; position:absolute; top:" + startPoint["y"] + "px; left:" + startPoint["x"] + "px; background-color:" + bgColor + "; line-height:" + lineWidth + ";\"></div>";
                    if (window["线段缓存"] == null) {
                        window["线段缓存"] = {};
                    }
                    if (window["线段缓存"]["h"] == null) {
                        window["线段缓存"]["h"] = {};
                    }
                    window["线段缓存"]["h"]["drawOutLine_" + window["linesTotalCount"]] = length;
                }
            }

            if (direction == "v" || direction == "V") {
                length = endPoint["y"] - startPoint["y"];
                endPoint = getAbsolutPosition(originalPoint, endPoint);

                endPoint["x"] = endPoint["x"] - lineWidth / 2;
                window["linesTotalCount"] = window["linesTotalCount"] + 1;
                if (type != "normal") {
                    htmlStr = "<div id=\"drawOutLine_" + window["linesTotalCount"] + "\"   style=\"width:" + lineWidth + "px;height:" + length + "px; position:absolute; top:" + endPoint["y"] + "px; left:" + endPoint["x"] + "px; background-color:" + bgColor + "; line-height:" + length + ";\"></div>";
                    //添加箭头
                    if (type == "axis") {
                        drawArrow(direction, endPoint, containerID, originalPoint);
                    }
                }
                else {
                    htmlStr = "<div id=\"drawOutLine_" + window["linesTotalCount"] + "\"   style=\"width:" + lineWidth + "px; position:absolute; top:" + endPoint["y"] + "px; left:" + endPoint["x"] + "px; background-color:" + bgColor + "; line-height:" + length + ";\"></div>";
                    if (window["线段缓存"] == null) {
                        window["线段缓存"] = {};
                    }
                    if (window["线段缓存"]["v"] == null) {
                        window["线段缓存"]["v"] = {};
                    }
                    window["线段缓存"]["v"]["drawOutLine_" + window["linesTotalCount"]] = length;
                }
            }

            container.append(htmlStr);

            //添加文字
            if (textToShow != null && jQuery.trim(textToShow) != "") {
                if (type == "normal") {
                    jQuery("div#drawOutLine_" + window["linesTotalCount"]).attr("title", textToShow);
                }
                if (type == "scale" || type == "axis") {
                    var textPosition = {};
                    textPosition["x"] = 0;
                    textPosition["y"] = 0;
                    
                    if (direction == "v" || direction == "V") {
                        if(startPoint["y"]<0){
                            textPosition["y"]=startPoint["y"];
                        }
                        if(endPoint["y"]<0)
                        {
                            textPosition["y"]=endPoint["y"];
                        }
                        textPosition["x"] = startPoint["x"] - textToShow.length*4.2;
                    }

                    if (direction == "h" || direction == "H") {
                        if (startPoint["x"] < 0) {
                            textPosition["x"] = startPoint["x"];
                        }
                        if (endPoint["x"] < 0) {
                            textPosition["x"] = endPoint["x"];
                        }
                        textPosition["x"] = textPosition["x"] - 8 * textToShow.length;
                        textPosition["y"] = endPoint["y"]+6.6;
                    }

                    textPosition = getAbsolutPosition(originalPoint, textPosition);
                    var textShower = "<div style=\"position:absolute; top:" + textPosition["y"] + "px; left:" + textPosition["x"] + "px;\">" + textToShow + "</div>";
                    container.append(textShower);
                }
            }
        }
    </script>
    <!-- 从相对坐标,获得绝对坐标 -->
    <script type="text/javascript">
        function getAbsolutPosition(originalPoint, relativePoint) {
            var result = {};
            result["x"] = originalPoint["x"] + relativePoint["x"];
            result["y"] = originalPoint["y"] - relativePoint["y"]
            return result;
        }
    </script>
    <!-- 获得原点 x,y 坐标 -->
    <script type="text/javascript">
        function getOriginalPoint(containerID) {
            var originalPoint = {};
            var y = jQuery("#" + containerID).offset().top + jQuery("#" + containerID).height() - window["原点偏移量y"];
            var x = jQuery("#" + containerID).offset().left + window["原点偏移量x"];
            originalPoint["x"] = x;
            originalPoint["y"] = y;
            return originalPoint;
        }
    </script>
    <!-- 将日期、开始时间、结束时间 转换为 x,y 坐标 -->
    <script type="text/javascript">
        function changDateAndTimeToXY(date, startTime, endTime, dateArray, TimeArray) {
            var startPoint = {};
            var endPoint = {};
            var result = {};
            result["startPoint"] = startPoint;
            result["endPoint"] = endPoint;
            //计算 y 坐标
            for (var i = 0; i < dateArray.length; i++) {
                if (date == dateArray[i]["coordinateText"]) {
                    startPoint["y"] = dateArray[i]["y"] + window["线条宽度"];
                    endPoint["y"] = dateArray[i]["y"] + window["线条宽度"];
                }
            }
            //计算 start x 坐标
            var startDateTime;
            for (var i = 0; i < TimeArray.length; i++) {
                startDateTime = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2], startTime.split(":")[0], startTime.split(":")[1], 0, 999);
                var itemTime = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2], TimeArray[i]["coordinateText"].split(":")[0], TimeArray[i]["coordinateText"].split(":")[1], 0, 999);
                if ((startDateTime - itemTime)==0) {
                    startPoint["x"] = TimeArray[i]["x"];
                    break;
                }
                if (startDateTime > itemTime) {
                    //比较时间,按比例,摆放位置
                    var firstDateTimeStr=date+" "+TimeArray[i]["coordinateText"];
                    var secondeDateTimeStr=date+" "+TimeArray[i+1]["coordinateText"];
                    var startDateTimeStr=date+" "+startTime;
                    var totalMinutes = GetDateDiff(firstDateTimeStr, secondeDateTimeStr, "minute");
                    var firstToStartTimeMintes = GetDateDiff(firstDateTimeStr, startDateTimeStr, "minute");
                    startPoint["x"] = TimeArray[i]["x"] + (TimeArray[i + 1]["x"] - TimeArray[i]["x"]) / totalMinutes * firstToStartTimeMintes;
                    break;
                }
            }
            //计算 end x 坐标
            var endDateTime;
            for (var i = 0; i < TimeArray.length; i++) {
                endDateTime = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2], endTime.split(":")[0], endTime.split(":")[1], 0, 999);
                var itemTime = new Date(date.split("-")[0], date.split("-")[1], date.split("-")[2], TimeArray[i]["coordinateText"].split(":")[0], TimeArray[i]["coordinateText"].split(":")[1], 0, 999);
                if ((endDateTime - itemTime)==0) {
                    endPoint["x"] = TimeArray[i]["x"];
                    break;
                }
                if (itemTime > endDateTime) {
                    var firstDateTimeStr = date + " " + TimeArray[i - 1]["coordinateText"];
                    var secondeDateTimeStr = date + " " + TimeArray[i]["coordinateText"];
                    var endDateTimeStr = date + " " + endTime;
                    var totalMinutes = GetDateDiff(firstDateTimeStr, secondeDateTimeStr, "minute");
                    var firstToEndTimeMintes = GetDateDiff(firstDateTimeStr, endDateTimeStr, "minute");
                    endPoint["x"] = TimeArray[i - 1]["x"] + (TimeArray[i]["x"] - TimeArray[i - 1]["x"]) / totalMinutes * firstToEndTimeMintes;
                    break;
                }
            }

            return result;
        }
    </script>
    <script type="text/javascript">
        /*
        * 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时:分钟:秒
        * 其中,年月日为全格式,例如 : 2010-10-12 01:00:00
        * 返回精度为:秒,分,小时,天
        */

        function GetDateDiff(startTime, endTime, diffType) {
            //将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式
            startTime = startTime.replace(/\-/g, "/");
            endTime = endTime.replace(/\-/g, "/");

            //将计算间隔类性字符转换为小写
            diffType = diffType.toLowerCase();
            var sTime = new Date(startTime);      //开始时间
            var eTime = new Date(endTime);  //结束时间
            //作为除数的数字
            var divNum = 1;
            switch (diffType) {
                case "second":
                    divNum = 1000;
                    break;
                case "minute":
                    divNum = 1000 * 60;
                    break;
                case "hour":
                    divNum = 1000 * 3600;
                    break;
                case "day":
                    divNum = 1000 * 3600 * 24;
                    break;
                default:
                    break;
            }
            return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
        }
    </script>
    <!-- 动画显示数据 -->
    <script type="text/javascript">
        function drawNormalLines() {
            if (window["线段缓存"] != null) {
                if (window["线段缓存"]["h"] != null) {
                    for (var id in window["线段缓存"]["h"]) {
                        var length=window["线段缓存"]["h"][id];
                        $("div#" + id).animate({ width: length }, window["显示速度"]);
                    }
                }
                if (window["线段缓存"]["v"] != null) {
                    var length = window["线段缓存"]["h"][id];
                    $("div#" + id).animate({ height: length }, window["显示速度"]);
                }
            }
        }
    </script>
    <!-- 开始绘制 -->
    <script type="text/javascript">
        var startPoint={};
        var endPoint={};

        //横坐标
        var vScaleItems = new Array();
        vScaleItems.push("");
        vScaleItems.push("2014-10-31");
        

        //纵坐标
        var hScaleItems = new Array();
        hScaleItems.push("8:00");
        hScaleItems.push("8:10");
        hScaleItems.push("8:20");
        hScaleItems.push("8:30");
        hScaleItems.push("8:40");
        hScaleItems.push("9:00");
        hScaleItems.push("9:10");
        hScaleItems.push("9:20");
        hScaleItems.push("9:30");
        hScaleItems.push("9:40");
        hScaleItems.push("9:50");
        hScaleItems.push("10:00");
        hScaleItems.push("10:10");
        hScaleItems.push("10:20");
        hScaleItems.push("10:30");
        hScaleItems.push("10:40");
        hScaleItems.push("10:50");
        hScaleItems.push("11:00");
        hScaleItems.push("11:10");
        hScaleItems.push("11:20");
        hScaleItems.push("11:30");
        hScaleItems.push("11:40");
        hScaleItems.push("11:50");
        hScaleItems.push("12:00");

        var vScaleItemsSource = drawCoordinates("v", vScaleItems, "true", window["辅助线颜色"]);
        var hScaleItemsSource = drawCoordinates("h", hScaleItems, "true", window["辅助线颜色"]);

        var startEndPointPair = changDateAndTimeToXY("2014-10-31", "09:00", "10:00", vScaleItemsSource, hScaleItemsSource);
        drawLineSegment(startEndPointPair["startPoint"], startEndPointPair["endPoint"], window["线条宽度"], "h", null, "#00f0f0", "6人");

        //画坐标
        drawCoordinates("v", vScaleItems, "true", window["辅助线颜色"]);
        drawCoordinates("h", hScaleItems, "true", window["辅助线颜色"]);
       //显示数据
       drawNormalLines();
    </script>
</body>
</html>



注:只加入了简单动画,尚未抽成插件,如有兴趣,请自行加强

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值