0

Me gustaría que alguien me ayudaría con el siguiente código ya que no tengo mucha experiencia en javascript y he estado intentando de varias maneras pero no logro que salga.

Quiero que el color de relleno del gráfico cambie de acuerdo a una condicional, es decir si el numero es mayor o menor a x muestre un color.

He escrito lo siguiente:

function liquidFillGaugeDefaultSettings(valor){

   if (valor <= 1){
      waveColor= "#00000";    // The color of the fill wave.
      circleColor= "#00000";   // The color of the outer circle.
      textColor= "#00000";     // The color of the value text.

        waveTextColor= "#00000"; // The color of the text when under wave. 

   }
       return {

        circleColor: "#1570b5",   // The color of the outer circle.
        textColor: "#1570b5",     // The color of the value text.
        waveColor: "#479ee5",    // The color of the fill wave.
        waveTextColor: "#0065ff", // The color of the text when under wave.             
        minValue: 0,              // The gauge minimum value.
        maxValue: 4,            // The gauge maximum value.
        circleThickness: 0.05,    // The outer circle thickness as a perc
        circleFillGap: 0.05,      // gap between the outer circle and wave circle 
        waveHeight: 0.05,         // The wave height as a perc
        waveCount: 0.5,             // The number of full waves per width
        waveRiseTime: 1000,       // The amount of time in milliseconds 
        waveAnimateTime: 12000,   // The amount of time in milliseconds
        waveRise: true,           // Control if the wave should rise from 0
        waveHeightScaling: true,  // Controls wave size scaling 
        waveAnimate: true,        // Controls if the wave scrolls or is static.
        waveOffset: 0,            // The amount to initially offset the wave. 
        textVertPosition: .5,     // The height at which to display
        textSize: 1,              // The relative height of the text 
        valueCountUp: true,       // If true, the displayed value counts up from 0
        displayPercent: true,     // If true, a % symbol is displayed after the value.
    };

Acá pueden ver el código completo.

    <html>
  <style>
    h1{
        text-align:center;
        color:#a6aaad;
        font-size:14px;
        font-family:verdana;
    }
    p{
            text-align:center;
        color:#425c84;
        font-size:20px;
        font-family:verdana;
      font-weight: bolder;
    }
  </style>
<body>
<h1># Fallos Canales </h1>
  <p>{Query.Falloscanales}</p>
 <script>
  var dato = parseFloat('{Query.PorcentajeFalloCanales}');   
  var value = dato;  
</script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<svg id="fillgauge1" width="100%" height="110"></svg>
<style>
    #fillgauge1{margin-top:20px;}
    .liquidFillGaugeText { font-family: Helvetica; font-weight: bold;}
</style>
<script>
     function liquidFillGaugeDefaultSettings(valor){

       if (valor <= 1){
          waveColor= "#00000";    // The color of the fill wave.
          circleColor= "#00000";   // The color of the outer circle.
          textColor= "#00000";     // The color of the value text.

            waveTextColor= "#00000"; // The color of the text when under wave. 

       }
           return {

            circleColor: "#1570b5",   // The color of the outer circle.
            textColor: "#1570b5",     // The color of the value text.
            waveColor: "#479ee5",    // The color of the fill wave.
            waveTextColor: "#0065ff", // The color of the text when under wave.             
            minValue: 0,              // The gauge minimum value.
            maxValue: 4,            // The gauge maximum value.
            circleThickness: 0.05,    // The outer circle thickness as a perc
            circleFillGap: 0.05,      // gap between the outer circle and wave circle 
            waveHeight: 0.05,         // The wave height as a perc
            waveCount: 0.5,             // The number of full waves per width
            waveRiseTime: 1000,       // The amount of time in milliseconds 
            waveAnimateTime: 12000,   // The amount of time in milliseconds
            waveRise: true,           // Control if the wave should rise from 0
            waveHeightScaling: true,  // Controls wave size scaling 
            waveAnimate: true,        // Controls if the wave scrolls or is static.
            waveOffset: 0,            // The amount to initially offset the wave. 
            textVertPosition: .5,     // The height at which to display
            textSize: 1,              // The relative height of the text 
            valueCountUp: true,       // If true, the displayed value counts up from 0
            displayPercent: true,     // If true, a % symbol is displayed after the value.
        };
    }
    function loadLiquidFillGauge(elementId, value, config) {
        if(config == null) config = liquidFillGaugeDefaultSettings(value);
        var gauge = d3.select("#" + elementId);
        var radius = Math.min(parseFloat(gauge.style("width")), parseFloat(gauge.style("height")))/2;
        var locationX = parseFloat(gauge.style("width"))/2 - radius;
        var locationY = parseFloat(gauge.style("height"))/2 - radius;
        var fillPercent = Math.max(config.minValue, Math.min(config.maxValue, value))/config.maxValue;
        var waveHeightScale;
        if(config.waveHeightScaling){
            waveHeightScale = d3.scale.linear()
                .range([0,config.waveHeight,0])
                .domain([0,50,100]);
        } else {
            waveHeightScale = d3.scale.linear()
                .range([config.waveHeight,config.waveHeight])
                .domain([0,100]);
        }
        var textPixels = (config.textSize*radius/2);
        var textFinalValue = parseFloat(value).toFixed(2);
        var textStartValue = config.valueCountUp?config.minValue:textFinalValue;
        var percentText = config.displayPercent?"%":"";
        var circleThickness = config.circleThickness * radius;
        var circleFillGap = config.circleFillGap * radius;
        var fillCircleMargin = circleThickness + circleFillGap;
        var fillCircleRadius = radius - fillCircleMargin;
        var waveHeight = fillCircleRadius*waveHeightScale(fillPercent*100);
        var waveLength = fillCircleRadius*2/config.waveCount;
        var waveClipCount = 1+config.waveCount;
        var waveClipWidth = waveLength*waveClipCount;
        var textRounder = function(value){ return Math.round(value); };
        if(parseFloat(textFinalValue) != parseFloat(textRounder(textFinalValue))){
            textRounder = function(value){ return parseFloat(value).toFixed(1); };
        }
        if(parseFloat(textFinalValue) != parseFloat(textRounder(textFinalValue))){
            textRounder = function(value){ return parseFloat(value).toFixed(2); };
        }
        var data = [];
        for(var i = 0; i <= 40*waveClipCount; i++){
            data.push({x: i/(40*waveClipCount), y: (i/(40))});
        }
        var gaugeCircleX = d3.scale.linear().range([0,2*Math.PI]).domain([0,1]);
        var gaugeCircleY = d3.scale.linear().range([0,radius]).domain([0,radius]);
        var waveScaleX = d3.scale.linear().range([0,waveClipWidth]).domain([0,1]);
        var waveScaleY = d3.scale.linear().range([0,waveHeight]).domain([0,1]);
        var waveRiseScale = d3.scale.linear()
            .range([(fillCircleMargin+fillCircleRadius*2+waveHeight),(fillCircleMargin-waveHeight)])
            .domain([0,1]);
        var waveAnimateScale = d3.scale.linear()
            .range([0, waveClipWidth-fillCircleRadius*2])
            .domain([0,1]);
        var textRiseScaleY = d3.scale.linear()
            .range([fillCircleMargin+fillCircleRadius*2,(fillCircleMargin+textPixels*0.7)])
            .domain([0,1]);
        var gaugeGroup = gauge.append("g")
            .attr('transform','translate('+locationX+','+locationY+')');
        var gaugeCircleArc = d3.svg.arc()
            .startAngle(gaugeCircleX(0))
            .endAngle(gaugeCircleX(1))
            .outerRadius(gaugeCircleY(radius))
            .innerRadius(gaugeCircleY(radius-circleThickness));
        gaugeGroup.append("path")
            .attr("d", gaugeCircleArc)
            .style("fill", config.circleColor)// MC9: Aquí asigna el color del círculo
            .attr('transform','translate('+radius+','+radius+')');
        var text1 = gaugeGroup.append("text")
            .text(textRounder(textStartValue) + percentText)
            .attr("class", "liquidFillGaugeText")
            .attr("text-anchor", "middle")
            .attr("font-size", textPixels + "px")
            .style("fill", config.textColor) // MC9: Aquí asigna el color del número%
            .attr('transform','translate('+radius+','+textRiseScaleY(config.textVertPosition)+')');
        var clipArea = d3.svg.area()
            .x(function(d) { return waveScaleX(d.x); } )
            .y0(function(d) { return waveScaleY(Math.sin(Math.PI*2*config.waveOffset*-1 + Math.PI*2*(1-config.waveCount) + d.y*2*Math.PI));} )
            .y1(function(d) { return (fillCircleRadius*2 + waveHeight); } );
        var waveGroup = gaugeGroup.append("defs")
            .append("clipPath")
            .attr("id", "clipWave" + elementId);
        var wave = waveGroup.append("path")
            .datum(data)
            .attr("d", clipArea)
            .attr("T", 0);
        var fillCircleGroup = gaugeGroup.append("g")
            .attr("clip-path", "url(#clipWave" + elementId + ")");
        fillCircleGroup.append("circle")
            .attr("cx", radius)
            .attr("cy", radius)
            .attr("r", fillCircleRadius)
            .style("fill", config.waveColor);//MC9 Aquí asigna el color de la ola
        var text2 = fillCircleGroup.append("text")
            .text(textRounder(textStartValue) + percentText)
            .attr("class", "liquidFillGaugeText")
            .attr("text-anchor", "middle")
            .attr("font-size", textPixels + "px")
            .style("fill", config.waveTextColor)
            .attr('transform','translate('+radius+','+textRiseScaleY(config.textVertPosition)+')');
        if(config.valueCountUp){
            var textTween = function(){
                var i = d3.interpolate(this.textContent, textFinalValue);
                return function(t) { this.textContent = textRounder(i(t)) + percentText; }
            };
            text1.transition()
                .duration(config.waveRiseTime)
                .tween("text", textTween);
            text2.transition()
                .duration(config.waveRiseTime)
                .tween("text", textTween);
        }
        var waveGroupXPosition = fillCircleMargin+fillCircleRadius*2-waveClipWidth;
        if(config.waveRise){
            waveGroup.attr('transform','translate('+waveGroupXPosition+','+waveRiseScale(0)+')')
                .transition()
                .duration(config.waveRiseTime)
                .attr('transform','translate('+waveGroupXPosition+','+waveRiseScale(fillPercent)+')')
                .each("start", function(){ wave.attr('transform','translate(1,0)'); }); 
        } else {
            waveGroup.attr('transform','translate('+waveGroupXPosition+','+waveRiseScale(fillPercent)+')');
        }
        if(config.waveAnimate) animateWave();
        function animateWave() {
            wave.attr('transform','translate('+waveAnimateScale(wave.attr('T'))+',0)');
            wave.transition()
                .duration(config.waveAnimateTime * (1-wave.attr('T')))
                .ease('linear')
                .attr('transform','translate('+waveAnimateScale(1)+',0)')
                .attr('T', 1)
                .each('end', function(){
                    wave.attr('T', 0);
                    animateWave(config.waveAnimateTime);
                });
        }
        function GaugeUpdater(){
            this.update = function(value){
                var newFinalValue = parseFloat(value).toFixed(2);
                var textRounderUpdater = function(value){ return Math.round(value); };
                if(parseFloat(newFinalValue) != parseFloat(textRounderUpdater(newFinalValue))){
                    textRounderUpdater = function(value){ return parseFloat(value).toFixed(1); };
                }
                if(parseFloat(newFinalValue) != parseFloat(textRounderUpdater(newFinalValue))){
                    textRounderUpdater = function(value){ return parseFloat(value).toFixed(2); };
                }
                var textTween = function(){
                    var i = d3.interpolate(this.textContent, parseFloat(value).toFixed(2));
                    return function(t) { this.textContent = textRounderUpdater(i(t)) + percentText; }
                };
                text1.transition()
                    .duration(config.waveRiseTime)
                    .tween("text", textTween);
                text2.transition()
                    .duration(config.waveRiseTime)
                    .tween("text", textTween);
                var fillPercent = Math.max(config.minValue, Math.min(config.maxValue, value))/config.maxValue;
                var waveHeight = fillCircleRadius*waveHeightScale(fillPercent*100);
                var waveRiseScale = d3.scale.linear()
                    .range([(fillCircleMargin+fillCircleRadius*2+waveHeight),(fillCircleMargin-waveHeight)])
                    .domain([0,1]);
                var newHeight = waveRiseScale(fillPercent);
                var waveScaleX = d3.scale.linear().range([0,waveClipWidth]).domain([0,1]);
                var waveScaleY = d3.scale.linear().range([0,waveHeight]).domain([0,1]);
                var newClipArea;
                if(config.waveHeightScaling){
                    newClipArea = d3.svg.area()
                        .x(function(d) { return waveScaleX(d.x); } )
                        .y0(function(d) { return waveScaleY(Math.sin(Math.PI*2*config.waveOffset*-1 + Math.PI*2*(1-config.waveCount) + d.y*2*Math.PI));} )
                        .y1(function(d) { return (fillCircleRadius*2 + waveHeight); } );
                } else { newClipArea = clipArea; }
                var newWavePosition = config.waveAnimate?waveAnimateScale(1):0;
                wave.transition()
                    .duration(0)
                    .transition()
                    .duration(config.waveAnimate?(config.waveAnimateTime * (1-wave.attr('T'))):(config.waveRiseTime))
                    .ease('linear')
                    .attr('d', newClipArea)
                    .attr('transform','translate('+newWavePosition+',0)')
                    .attr('T','1')
                    .each("end", function(){
                        if(config.waveAnimate){
                            wave.attr('transform','translate('+waveAnimateScale(0)+',0)'); animateWave(config.waveAnimateTime);
                        }
                    });
                waveGroup.transition()
                    .duration(config.waveRiseTime)
                    .attr('transform','translate('+waveGroupXPosition+','+newHeight+')')
            }
        }
        return new GaugeUpdater();
    }
   var gauge1 = loadLiquidFillGauge("fillgauge1", value);
</script>

  </body>  
</html>

introducir el código aquí

1
  • Bienvenido @Jhon Edison Gutierrez Barbosa a Stack Overflow en español, te sugiero que hagas el recorrido y de paso ganes tu primera medalla, también es muy importante que leas Cómo preguntar para poder mejorar tu pregunta y que sea bien recibida por la comunidad, favoreciendo tus chances de obtener buenas respuestas. el 8 mar. 2019 a las 3:12

1 respuesta 1

0

Veo que tienes la idea, pero te falta completarla. Lo que debes hacer es en primer lugar declarar las variables, ya que tendrán sólo ámbito local, luego debes usar el condicional if...else para asignarle el valor adecuado a cada variable. Por último, en el objeto que devuelve tu función pasas esas variables como valores de los atributos respectivos.

Una forma en la que puede quedar el código es la siguiente:

function liquidFillGaugeDefaultSettings(valor){
    //declaramos las variables aquí para que tengan ámbito local
    var circleColor;   // The color of the outer circle.
    var textColor;     // The color of the value text.
    var waveColor;     // The color of the fill wave.
    var waveTextColor; // The color of the text when under wave. 
    // usamos el condicional para establecer el valor de cada variable
    if (valor <= 1){
        circleColor= "#00000";
        textColor= "#00000";
        waveColor= "#00000";
        waveTextColor= "#00000";
    } else {  // aqui establecemos el valor que tendrá si no se cumple la condición
        circleColor = "#1570b5";
        textColor = "#1570b5";
        waveColor = "#479ee5";
        waveTextColor = "#0065ff";
    }
    return {
        // Aquí pasaremos nuestras variables como valores de cada atributo
        circleColor: circleColor,   // The color of the outer circle.
        textColor: textColor,     // The color of the value text.
        waveColor: waveColor,    // The color of the fill wave.
        waveTextColor: waveTextColor, // The color of the text when under wave.
        // El resto es tu código que no se ha alterado
        minValue: 0,              // The gauge minimum value.
        maxValue: 4,            // The gauge maximum value.
        circleThickness: 0.05,    // The outer circle thickness as a perc
        circleFillGap: 0.05,      // gap between the outer circle and wave circle 
        waveHeight: 0.05,         // The wave height as a perc
        waveCount: 0.5,             // The number of full waves per width
        waveRiseTime: 1000,       // The amount of time in milliseconds 
        waveAnimateTime: 12000,   // The amount of time in milliseconds
        waveRise: true,           // Control if the wave should rise from 0
        waveHeightScaling: true,  // Controls wave size scaling 
        waveAnimate: true,        // Controls if the wave scrolls or is static.
        waveOffset: 0,            // The amount to initially offset the wave. 
        textVertPosition: .5,     // The height at which to display
        textSize: 1,              // The relative height of the text 
        valueCountUp: true,       // If true, the displayed value counts up from 0
        displayPercent: true,     // If true, a % symbol is displayed after the value.
    };
}

// Hacemos pruebas:

//Pasamos un valor menor que 1
var resultado_1 = liquidFillGaugeDefaultSettings(0);

//Pasamos un valor mayor que 1
var resultado_2 = liquidFillGaugeDefaultSettings(2);

//Mostramos el resultado para ambos casos
console.log('resultado_1.circleColor: ', resultado_1.circleColor);

console.log('resultado_2.circleColor: ', resultado_2.circleColor);

Espero que esto te ayude a solucionar el problema.

2

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.