d3.js 教程 模仿echarts柱状图

vadim-web 2019-09-03 原文

d3.js 教程 模仿echarts柱状图

由于最近工作不是很忙,隧由把之前的charts项目用d3.js重写的一下,其实d3.js文档很多,但是入门不是很难,可是想真的能做一个完成的,交互良好的图还是要下一番功夫的。今天在echarts找到了一个柱状图,如图。

模仿了一番,废话不多说。下面就开始我们的代码(注意是D3.v4版本)。

1. js 类

class Bar {
    constructor() {
        this._width = 1000;
        this._height = 700;
        this._padding = 10;
        this._offset = 35;
        this._margins = {right: 40,bottom: 40,left: 40,top: 40};
        this._scaleX = d3.scaleBand().rangeRound([0, this._width - this._margins.left - this._margins.right]);
        this._scaleY = d3.scaleLinear().range([this._height - this._margins.top - this._margins.bottom, 0]);
        this._color = '#3398DB';
        this._data = [];
        this._svg = null;
        this._body = null;
        this._tooltip = null;
        this._shadow = null;
        this._ticks = 5;
        this._key = 'key';
        this._value = 'value';
    }
    render() {
        if(!this._tooltip) {
            this._tooltip = d3.select('body')
            .append('div')
            .style('left', '40px')
            .style('top', '30px')
            .attr('class', 'tooltip')
            .html('');
        }
        if(!this._svg) {
            this._svg = d3.select('body')
                .append('svg')
                .attr('width', this._width)
                .attr('height', this._height)
            this.renderAxes();
            this.renderClipPath();
        }
        this.renderBody();
    }
    renderAxes() {
        let axes = this._svg.append('g')
            .attr('class', 'axes');

        this.renderXAxis(axes);
        this.renderYAxis(axes);
    }
    renderXAxis(axes) {
        let xAxis = d3.axisBottom().scale(this._scaleX)
        axes.append('g')
            .attr('class', 'x axis')
            .attr('transform', `translate(${this.xStart()}, ${this.yStart()})`)
            .call(xAxis)
    }
    renderYAxis(axes) {
        let yAxis = d3.axisLeft().scale(this._scaleY).ticks(this._ticks);
        axes.append('g')
            .attr('class', 'y axis')
            .attr('transform', `translate(${this.xStart()}, ${this.yEnd()})`)
            .call(yAxis)

        d3.selectAll('.y .tick')
            .append('line')
            .attr('class', 'grid-line')
            .attr('x1', 0)
            .attr('y1', 0)
            .attr('x2', this.quadrantWidth())
            .attr('y2', 0)
    }
    renderClipPath() {
        this._svg.append('defs')
            .append('clip-path')
            .attr('id', 'body-clip')
            .append('rect')
            .attr('x', 0)
            .attr('y', 0)
            .attr('width', this.quadrantWidth())
            .attr('height', this.quadrantHeight())
    }
    renderBody() {
        if(!this._body) {
            this._body = this._svg.append('g')
                .attr('class', 'body')
                .attr('transform', `translate(${this._margins.left},${this._margins.top})`)
                .attr('clip-path', 'url(#clipPath)')
            this.renderShadow()
        }
        this.renderBar();
        this.listenMousemove();
    }
    renderShadow() {
        this._shadow = this._body.append('rect')
            .attr('x', 0)
            .attr('y', 0)
            .attr('width', this.everyWidth())
            .attr('height', this._scaleY(0))
            .attr('fill', '#000')
            .attr('fill-opacity', 0)
    }
    renderBar() {
        let barElements = this._body
            .selectAll('rect.bar')
            .data(this._data);

        let barEnter =  barElements
            .enter()
            .append('rect')
            .attr('class', 'bar')
            .attr('x', d => this._scaleX(d[this._key]) + this.everyWidth() * 0.18)
            .attr('y', () => this._scaleY(0))
            .attr('width', this.everyWidth() * 0.64)
            .attr('height', () => this.quadrantHeight() - this._scaleY(0))

        let barUpdate = barEnter
            .merge(barElements)
            .transition()
            .duration(800)
            .ease(d3.easeCubicOut)
            .attr('y', d => this._scaleY(d[this._value]))
            .attr('height', d => {
                console.log(this.quadrantHeight() - this._scaleY(d[this._value]))
                return this.quadrantHeight() - this._scaleY(d[this._value])
            });

        let barExit = barElements
            .exit()
            .transition()
            .attr('y', () => this._scaleY(0))
            .attr('height', () => this.quadrantHeight() - this._scaleY(0))
            .remove();
    }
    listenMousemove() {
        this._svg.on('mousemove', () => {
            let px = d3.event.offsetX;
            let py = d3.event.offsetY;
            if(px < this.xEnd() && px > this.xStart() && py < this.yStart() && py > this.yEnd()) {
                this.renderShadowAndTooltip(px, py, px - this.xStart());
            } else {
                this.hideShadowAndTooltip();
            }
        })
    }
    renderShadowAndTooltip(x, y, bodyX) {
        let cutIndex = Math.floor(bodyX / this.everyWidth());
        this._shadow.transition().duration(50).ease(d3.easeLinear).attr('fill-opacity', .12).attr('x', cutIndex * this.everyWidth());
        if(x > this.quadrantWidth() - this._tooltip.style('width').slice(0,-2) - this._padding * 2) {
            x = x - this._tooltip.style('width').slice(0,-2) - this._padding * 2 - this._offset * 2;
        }
        if(y > this.quadrantHeight() - this._tooltip.style('height').slice(0,-2) - this._padding * 2) {
            y = y - this._tooltip.style('height').slice(0,-2) - this._padding * 2 - this._offset * 2;
        }
        this._tooltip.html(`${this._data[cutIndex][this._key]}<br/>数量统计: ${this._data[cutIndex][this._value]}`).transition().duration(100).ease(d3.easeLinear).style('display', 'inline-block').style('opacity', .6).style('left', `${x + this._offset + this._padding}px`).style('top', `${y + this._offset + this._padding}px`);
    }
    hideShadowAndTooltip() {}
    everyWidth() {
        return this.quadrantWidth() / this._data.length;
    }
    quadrantWidth() {
        return this._width - this._margins.left - this._margins.right;
    }
    quadrantHeight() {
        return this._height - this._margins.top - this._margins.bottom;
    }
    xStart() {
        return this._margins.left;
    }
    xEnd() {
        return this._width - this._margins.right;
    }
    yStart() {
        return this._height - this._margins.bottom;
    }
    yEnd() {
        return this._margins.top;
    }
    scaleX(a) {
        this._scaleX = this._scaleX.domain(a);
    }
    scaleY(a) {
        this._scaleY = this._scaleY.domain(a)
    }
    key(k) {
        if(!arguments.length) return this._key;
        this._key = k;
        this.scaleX(this._data.map(d => d[this._key]))
        return this;
    }
    value(v) {
        if(!arguments.length) return this._value;
        this._value = v;
        let arr = this._data.map(d => d[this._value]);
        let ele = Math.pow(10, d3.max(arr).toString().length - 1);
        let max = Math.ceil(d3.max(arr) / ele) * ele;
        this.scaleY([0, max]);
        return this;
    }
    data(data) {
        if(!arguments.length) return this._data;
        this._data = data;
        return this;
    }
}

2 CSS 文件很简单

.domain {
  stroke-width: 2;
  fill: none;
  stroke: #888;
  shape-rendering: crispEdges;
}
.x .tick line {
  opacity: 0  ;
}
.tick text {
  font-size: 14px;
}
.grid-line {
  fill: none;
  stroke: #888;
  opacity: .4;
  shape-rendering: crispEdges;
}
.bar {
  fill: #3398DB;
}
.tooltip{
  font-size: 15px;
  width: auto;
  padding: 10px;
  height: auto;
  position: absolute;
  text-align: center;
  background-color: #000000;
  opacity: .6;
  border-radius:5px;
  color: #ffffff;
  display: none;
}

3 加下来就是html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$Title$</title>
    <link rel="stylesheet" type="text/css" href="css/base.css"/>
    <script type="text/javascript" src="js/d3.v4.js"></script>
    <script type="text/javascript" src="js/bar.js"></script>
</head>
<body>
<script>
    var dataset = [{date: 'Mon', label: 15},{date: 'Tue', label: 52},{date: 'Wed', label: 200},{date: 'Thu', label: 235},{date: 'Fri', label: 390},{date: 'Sat', label: 330},{date: 'Sun', label: 221}];
    var bar = new Bar();
    bar
        .data(dataset)
        .key('date')
        .value('label')
        .render();
</script>
</body>
</html>

4 接着是效果图

新上手的朋友们可以先学习一下ES6,然后在学习类的思想,d3.v3和v4 v5的版本差异比较大,直接学习d3.v4就可以了,最最后推荐一本书。D3 4.x数据可视化实战手册。这本书比较基础但是能够通过它养成良好的d3编程习惯。祝大家d3学习顺利。

如果想下载代码或者预览这个DEMO请移步到原文!!!

原文链接:http://www.bettersmile.cn

发表于
2019-09-03 22:37 Vadim 阅读() 评论() 编辑 收藏

 

版权声明:本文为vadim-web原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/vadim-web/p/11456188.html

d3.js 教程 模仿echarts柱状图的更多相关文章

  1. hbuilderx+香蕉云编生成ios证书和上架教程

    现在很多公司都使用uniapp作为底层框架来开发app应用,而uniapp的开发工具hbuilderx云打包的时候,需要证书和证书profile文件。假如是ios应用,则还需要上架到appstore.假如是安卓应用,生成证书很简单,使...

  2. CentOS8 安装 Mysql8 教程

    Mysql8安装教程 操作系统版本:CentOS Linux release 8.3 Mysql版本:Mysq […]...

  3. 教程——如何在Mac上 安装+破解 Office2016

    声明 有条件的用户可以在微软官网购买正版的的激活码,请用户们支持正版。该教程旨在分享。 为啥写这篇文章 对于大 […]...

  4. d3.js 教程 模仿echarts legend功能

    上一节记录没有加上echarts的legend功能,这一小节补一下。 1. 数据 我们可以从echarts中看 […]...

  5. 用 k8s 管理机密信息 – 每天5分钟玩转 Docker 容器技术(155)

    应用启动过程中可能需要一些敏感信息,比如访问数据库的用户名密码或者秘钥。将这些信息直接保存在容器镜像中显然不妥 […]...

  6. Python中的多进程、多线程和协程

    本文中的内容来自我的笔记。撰写过程中参考了胡俊峰老师《Python程序设计与数据科学导论》课程的内容。 并发处 […]...

  7. 如何实现windows命令提示符的tab补全?

    如何实现windows命令提示符的tab补全? 也许有人说win下的cmd的TAB键不都是自动补全的吗?其实不 […]...

  8. python学习笔记

    标签: python 自制教程 [TOC] ##一:语法元素 ###1.注释,变量,空格的使用 注释 单行注释 […]...

随机推荐

  1. [flex 布局]——flex教程

    简介:2009年,W3C提出了一种新的方案—-Flex布局,可以简便、完整、响应式地实现各种页面布 […]...

  2. 简单配置vps,防ddos攻击

    防人之心不可无。 网上总有些无聊或者有意的人。不多说了。上干货,配置vps apf防小流量ddos攻击。 对于 […]...

  3. HTML5游戏开发,剪刀石头布小游戏案例

    http://www.j–d.com/wp-content/uploads/2015/05/QQ截 […]...

  4. 成都UI设计师工资是多少?工资高吗?

    目前成都UI设计已经成为电脑设计行业里的热词。UI设计是用户界面设计的简称,指的是对软件的人机交互、操作逻辑、 […]...

  5. 云服务器初尝试 – zhuxq

    云服务器初尝试 阿里云服务器 购买 登录   本人购买了阿里云服务器~准备部署个项目上去   一、购买阿里云服 […]...

  6. 深入学习Netty(4)——Netty编程入门

    前言   从学习过BIO、NIO、AIO编程之后,就能很清楚Netty编程的优势,为什么选择Netty,而不是 […]...

  7. 分享3一个博客HTML5模板

    1.材类别:半透明 博客html模板 个人博客半透明html5博客主题,半透明,博客,博客html模板,个人博 […]...

  8. C#.NET Winform快速开发框架权限系统详细设计(原创作品)

      一、权限系统基本概述   本文档描述了C/S系统快速开发框架旗舰版V5.0权限管理模块详细功能设计,权限实 […]...

展开目录

目录导航