美文网首页让前端飞Web前端之路
前端大屏幕项目(数据可视化)的一点思考

前端大屏幕项目(数据可视化)的一点思考

作者: 安东尼的漫长岁月 | 来源:发表于2019-08-16 14:15 被阅读33次

    想必近几年前端的数据可视化越来越重要了,很多甲方爸爸都喜欢那种炫酷的大屏幕设计,类似如下这种:


    随便找的.jpg

    遇到的这样的项目,二话不说,echarts或者antv,再搭配各种mvvm框架(react,vue),找二次封装过的组件,然后开始埋头开始写了,写着写着你会发现,如何适配不同屏幕呢?css媒体查询吧,用vw吧,哪个好点呢。其实写到最后,我觉得都不好

    对于这种拿不定主意的情况呢,最好还是参考大厂的做法,于是去找了网易有数,百度suger等,他们是如何写这样的页面的
    提供2个他们的案例链接:
    百度
    网易有数
    仔细观察他们都采用了css3的缩放transform: scale(X)属性,看到这是不是有种豁然开朗的感觉
    于是我们只要监听浏览器的窗口大小,然后控制变化的比例就好了
    以React的写法为例

    getScale=() => {
        // 固定好16:9的宽高比,计算出最合适的缩放比,宽高比可根据需要自行更改
        const {width=1920, height=1080} = this.props
        let ww=window.innerWidth/width
        let wh=window.innerHeight/height
        return ww<wh?ww: wh
    }
    setScale = debounce(() => {
        // 获取到缩放比,设置它
        let scale=this.getScale()
        this.setState({ scale })
    }, 500)
    

    监听window的resize事件最好加个节流函数debounce

    window.addEventListener('resize', this.setScale)
    

    然后一个完整的组件就封装好了

    import React, { Component } from 'react';
    import debounce from 'lodash.debounce'
    import s from './index.less'
    
    class Comp extends Component{
      constructor(p) {
        super(p)
        this.state={
          scale: this.getScale()
        }
      }
      componentDidMount() {
        this.setScale()
        window.addEventListener('resize', this.setScale)
      }
      getScale=() => {
        const {width=1920, height=1080} = this.props
        let ww=window.innerWidth/width
        let wh=window.innerHeight/height
        return ww<wh?ww: wh
      }
      setScale = debounce(() => {
        let scale=this.getScale()
        this.setState({ scale })
      }, 500)
      render() {
        const {width=1920, height=1080, children} = this.props
        const {scale} = this.state
        return(
          <div
            className={s['scale-box']}
            style={{
              transform: `scale(${scale}) translate(-50%, -50%)`,
              WebkitTransform: `scale(${scale}) translate(-50%, -50%)`,
              width,
              height
            }}
          >
            {children}
          </div>
        )
      }
      componentWillUnmount() {
        window.removeEventListener('resize', this.setScale)
      }
    }
    
    export default Comp
    
    .scale-box{
      transform-origin: 0 0;
      position: absolute;
      left: 50%;
      top: 50%;
      transition: 0.3s;
    }
    

    只要把页面放在这个组件中,就能实现跟大厂们类似的效果。这种方式下不管屏幕有多大,分辨率有多高,只要屏幕的比例跟你定的比例一致,都能呈现出完美效果。而且开发过程中,样式的单位也可以直接用px,省去了转换的烦恼~~~
    注:图表插件bizcharts在css缩放下会有鼠标移入时像素偏移的bug,由于是基于antv的,这主要是antv的bug,我写这篇文章的时候官方还未修复这个bug,echarts没有这个bug。

    相关文章

      网友评论

        本文标题:前端大屏幕项目(数据可视化)的一点思考

        本文链接:https://www.haomeiwen.com/subject/xfifsctx.html