仪表 D3,显示值位置

2023-12-31

我正在尝试使用一些现成的 JavaScript 来制作仪表。我快到了,但我不知道如何管理值标题。

Here is how my code works now: enter image description here

And this is how I like it to work: enter image description here

不知道如何处理问题。使用 Math.Pi、Math.cos 和 Math.sin 对我来说实在是太多了。

var name = "Value";

var value = 17;


var gaugeMaxValue = 100; 

// data to calculate 
var percentValue = value / gaugeMaxValue; 

////////////////////////

var needleClient;



(function(){

var barWidth, chart, chartInset, degToRad, repaintGauge,
    height, margin, numSections, padRad, percToDeg, percToRad, 
    percent, radius, sectionIndx, svg, totalPercent, width;



  percent = percentValue;

  numSections = 1;
  sectionPerc = 1 / numSections / 2;
  padRad = 0.025;
  chartInset = 10;

  // Orientation of gauge:
  totalPercent = .75;

  el = d3.select('.chart-gauge');

  margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 20
  };

  width = el[0][0].offsetWidth - margin.left - margin.right;
  height = width;
  radius = Math.min(width, height) / 2;
  barWidth = 40 * width / 300;



  //Utility methods 

  percToDeg = function(perc) {
    return perc * 360;
  };

  percToRad = function(perc) {
    return degToRad(percToDeg(perc));
  };

  degToRad = function(deg) {
    return deg * Math.PI / 180;
  };

  // Create SVG element
  svg = el.append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom);

  // Add layer for the panel
  chart = svg.append('g').attr('transform', "translate(" + ((width + margin.left) / 2) + ", " + ((height + margin.top) / 2) + ")");


  chart.append('path').attr('class', "arc chart-first");
  chart.append('path').attr('class', "arc chart-second");
  chart.append('path').attr('class', "arc chart-third");
  formatValue = d3.format('1%');
  

  


  arc3 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
  arc2 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)
  arc1 = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth)

  repaintGauge = function () 
  {
    perc = 45/100;
    var next_start = totalPercent;
    arcStartRad = percToRad(next_start);
    arcEndRad = arcStartRad + percToRad(perc / 2);
    next_start += perc / 2;


    arc1.startAngle(arcStartRad).endAngle(arcEndRad);

    perc = 1-perc;
    arcStartRad = percToRad(next_start);
    arcEndRad = arcStartRad + percToRad(perc / 2);
    next_start += perc / 2;

    arc2.startAngle(arcStartRad + padRad).endAngle(arcEndRad);

    chart.select(".chart-first").attr('d', arc1);
    chart.select(".chart-second").attr('d', arc2);
 


  }
/////////

    var dataset = [{metric:name, value: value}]

    var texts = svg.selectAll("text")
                .data(dataset)
                .enter();

    texts.append("text")
         .text(function(){
              return dataset[0].metric;
         })
         .attr('id', "Name")
         .attr('transform', "translate(" + ((width + margin.left) / 6) + ", " + ((height + margin.top) / 1.5) + ")")
         .attr("font-size",25)
         .style("fill", "#000000");


    texts.append("text")
         .text(function(){
            return dataset[0].value;
         })
         .attr('id', "Value")
         .attr('transform', "translate(" + ((width + margin.left) / 1.4) + ", " + ((height + margin.top) / 1.5) + ")")
         .attr("font-size",25)
         .style("fill", "#000000");




    texts.append("text")
        .text(function(){
            return 0;
        })
        .attr('id', 'scale0')
        .attr('transform', "translate(" + ((width + margin.left) / 100 ) + ", " + ((height + margin.top) / 2) + ")")
        .attr("font-size", 15)
        .style("fill", "#000000");

    texts.append("text")
        .text(function(){
            return gaugeMaxValue/2;
        })
        .attr('id', 'scale10')
        .attr('transform', "translate(" + ((width + margin.left) / 2.15 ) + ", " + ((height + margin.top) / 30) + ")")
        .attr("font-size", 15)
        .style("fill", "#000000");


    texts.append("text")
        .text(function(){
            return gaugeMaxValue;
        })
        .attr('id', 'scale20')
        .attr('transform', "translate(" + ((width + margin.left) / 1.03 ) + ", " + ((height + margin.top) / 2) + ")")
        .attr("font-size", 15)
        .style("fill", "#000000");

  var Needle = (function() {

    //Helper function that returns the `d` value for moving the needle
    var recalcPointerPos = function(perc) {
      var centerX, centerY, leftX, leftY, rightX, rightY, thetaRad, topX, topY;
      thetaRad = percToRad(perc / 2);
      centerX = 0;
      centerY = 0;
      topX = centerX - this.len * Math.cos(thetaRad);
      topY = centerY - this.len * Math.sin(thetaRad);
      leftX = centerX - this.radius * Math.cos(thetaRad - Math.PI / 2);
      leftY = centerY - this.radius * Math.sin(thetaRad - Math.PI / 2);
      rightX = centerX - this.radius * Math.cos(thetaRad + Math.PI / 2);
      rightY = centerY - this.radius * Math.sin(thetaRad + Math.PI / 2);
      return "M " + leftX + " " + leftY + " L " + topX + " " + topY + " L " + rightX + " " + rightY;
    };

    function Needle(el) {
      this.el = el;
      this.len = width / 2.5;
      this.radius = this.len / 8;
    }

    Needle.prototype.render = function() {
      this.el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius);

      return this.el.append('path').attr('class', 'needle').attr('id', 'client-needle').attr('d', recalcPointerPos.call(this, 0));


    };

    Needle.prototype.moveTo = function(perc) {
      var self,
          oldValue = this.perc || 0;

      this.perc = perc;
      self = this;

      // Reset pointer position
      this.el.transition().delay(100).ease('quad').duration(200).select('.needle').tween('reset-progress', function() {
        return function(percentOfPercent) {
          var progress = (1 - percentOfPercent) * oldValue;

          repaintGauge(progress);
          return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
        };
      });

      this.el.transition().delay(300).ease('bounce').duration(1500).select('.needle').tween('progress', function() {
        return function(percentOfPercent) {
          var progress = percentOfPercent * perc;

          repaintGauge(progress);
          return d3.select(this).attr('d', recalcPointerPos.call(self, progress));
        };
      });

    };


    return Needle;

  })();



  needle = new Needle(chart);
  needle.render();
  needle.moveTo(percent);   

})();
       <style type="text/css" src="gauge.css">
            .chart-gauge
            {
              width: 400px;
              margin: 100px auto  
             } 
            .chart-first
            {
                fill: #66AB8C;
            }
            .chart-second
            {
                fill: #ff533d;
            }
  

            .needle, .needle-center
            {
                fill: #000000;
            }
            .text {
                color: "#112864";
                font-size: 16px;
            }


            svg {
              font: 10px sans-serif;
            }


        </style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.0.0/d3.min.js"></script>
<div class="chart-gauge"></div>

这一切都是为了改变翻译text

例如(设置仪表的最大值):

  texts.append("text")
    .text(function() {
      return gaugeMaxValue + "%";//i added the percent(%)
    })
    .attr('id', 'scale20')
    .attr('transform', "translate(" + ((width + margin.left) / 1.08) + ", " + ((height + margin.top) / 2) + ")")//then change the x and y for the translate
    .attr("font-size", 15)
    .style("fill", "#000000");

对于所有其他文本值也是如此。

工作代码here https://plnkr.co/edit/LJlKKX1xnVwl2LoFBFoO

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仪表 D3,显示值位置 的相关文章

随机推荐

  • System.Net.FtpClient openwrite 不会上传文件,除非我在退出前插入睡眠

    我正在使用 System Net FtpClient 程序集将文件上传到测试 FTP 站点 当我运行下面的代码时 文件不会出现在远程位置 除非我按照下面的方式使用 Thread Sleep 我不想使用 using System using
  • 如何知道哪个列表项对用户可见?

    我通过我的应用程序录制了视频 并将其存储在存储卡中 在我获取这些视频并将其添加到列表视图后 根据屏幕尺寸 用户只能看到一个视频 如果用户上下滚动并停止 那时我想知道哪一个在用户面前 如果有人知道解决方案请帮助我 或任何其他方法 提前致谢 好
  • Apache Lucene TokenStream 合同违规

    使用 Appache Lucene TokenStream 删除停用词 导致错误 TokenStream contract violation reset close call missing reset called multiple t
  • Ceres Solver:无法禁用日志记录(google glog)

    我在一个项目中使用 ceres 求解器 当我调用ceres Solve函数后 库开始输出如下行 iterative schur complement solver cc 88 No parameter blocks left in the
  • 根据另一个 NSArray 字符串的排序对自定义对象的 NSArray 进行排序

    我有两个NSArray我想要以相同方式排序的对象 一个包含NSString对象 其他自定义Attribute对象 这是我的 关键 NSArray 的样子 The master order NSArray stringOrder NSArra
  • spring-boot 与 tomcat 和 cxf-servlet

    我正在尝试使用 spring boot 来建立嵌入式 Tomcat 我想在应用程序中使用 CXF 来提供一组 Web 服务 但我不知道如何建立 CXF servlet 我的主课看起来像这样 Configuration EnableAutoC
  • 在 Android 中使用相机活动

    如果您想使用使用本机 Android 相机的内置相机 Activity 只需执行以下操作即可 Intent camera new Intent MediaStore ACTION IMAGE CAPTURE this startActivi
  • 为什么我们仍然在 .NET 中使用数据集?

    数据集是 NET 1 0 中最重要的东西之一 即使现在使用 NET 3 5 我仍然发现自己必须使用它们 特别是当我必须调用一个返回数据集的存储过程时 我最终会得到该数据集手动转换为对象以使其更易于使用 我从来没有真正喜欢过数据集 并且发现它
  • django 将 .values_list('datetimefield') 转换为日期

    我想将带有日期时间对象的 value list 字段转换为日期对象 values list time finished flat True 给我 2016 03 22T18 52 53 486Z 我想要的是 2016 03 22 谢谢你 您
  • Autofac多次注册组件

    在上一个关于如何可视化依赖关系图的问题中 https stackoverflow com a 59247007 1955317我为现在用来可视化我的依赖关系图的代码奠定了基础 因为它是由 Autofac 解析的 运行代码 我得到一棵树 生成
  • 为什么java进程使用的内存比预期多得多

    系统信息 操作系统 archlinux JDK OpenJDK IcedTea 2 4 3 ArchLinux 版本 7 u45 2 4 3 1 x86 64 运行应用程序 https github com aemoncannon ensi
  • 是否可以将观察者添加到tableView.contentOffset?

    我需要跟踪 tableView contentOffset y 是否可以将观察者添加到 tableView contentOffset 我认为这是不可能的 因为 contentOffset 不继承 NSObject 类 还有其他解决办法吗
  • 将递归函数转换为异步 CPS 实现 (javascript)

    这是我的功能 function duplicate step through highlighted element jq target jq char cb console log element jq var contents elem
  • 如何在R中手动更改VisNetwork中节点的位置

    我的 VisNetwork 遇到问题 我在 R 中创建了一个图表 每次单击节点并将其移动到其他位置时 它都会回到之前的位置 是否有可能手动重新安排网络 我想将一些节点移动到其他位置或更改一些节点之间的边的长度 以便它更加透明 至少有两种可能
  • 我从 C 函数读取嵌套 lua 表作为参数是否正确?

    我将用C语言实现一个函数 该函数将由Lua脚本调用 这个函数应该接收一个lua表 甚至包含一个数组 作为参数 所以我应该读取表中的字段 我尝试像下面那样做 但是当我运行它时我的函数崩溃了 谁能帮我找出问题所在吗 function findI
  • Fedora 24 上的 libicu 和 stringi 导致 R 头痛

    我最近升级到 F24 现在在我的 R 会话中我无法加载一些包 sp reshape2 latex2exp knitr 等 我发现的最初问题是 F24 使用 libicu56 而这些软件包需要 libicu54 我遵循了一个建议这个线程 ht
  • 如何以编程方式更改 Chrome 中地址栏的字体大小

    我想以编程方式更改 Chrome 中地址栏的字体大小 因为它对我来说太大了 有什么办法可以做到这一点吗 通常 地址栏的字体大小由操作系统的默认字体大小决定 在这里阅读评论 https code google com p chromium i
  • 如何在 Java 中将十六进制字符串转换为字节值

    我有一个字符串数组 我想将它转换为字节数组 我使用Java程序 例如 String str aa 55 转换成 byte new byte 0xaa byte 0x55 我能做些什么 String str Your string byte
  • 通过ParentProcessID杀死进程

    我想通过其 ParentProcessID 终止正在运行的进程 我想像您在命令行中一样执行此操作 wmic process where parentprocessid 3008 terminate 但现在的问题是 在 PowerShell
  • 仪表 D3,显示值位置

    我正在尝试使用一些现成的 JavaScript 来制作仪表 我快到了 但我不知道如何管理值标题 Here is how my code works now And this is how I like it to work 不知道如何处理问