javascript - canvas 的 javascript 中的自定义渐变有一些错误

标签 javascript html canvas html5-canvas

对于一个项目,我正在尝试制作自己的线性渐变代码。我已经取得了很大的进步,但是,它并不完美。有些地方的渐变看起来并不像它应该的那样。

请参阅以下代码,其中 colorStops 是渐变中的停止点。它应该像交通灯一样显示红色、黄色和绿色之间的渐变。

gradientSlider = {
      colorStops: ["#b30000", "#ffff1a", "#00e600"],
      minValue: 0,
      maxValue: 100,
      init: function(canvas) {
        this.canvas = canvas;
        this.ctx = canvas.getContext("2d");
        this.width = canvas.width;
        this.height = canvas.height;
        this.colors = this.calculateHexColorForStep();
        this.draw();
      },
      draw: function() {
        pixelWidth = this.width / this.maxValue;
        for (i = 0; i < this.maxValue; i++) {
          this.ctx.beginPath();
          this.ctx.rect(i * pixelWidth, 0, pixelWidth, this.height);
          this.ctx.fillStyle = this.colors[i];
          this.ctx.fill();
        }
      },
      calculateHexColorForStep: function() {
        result = [];
        stepsPerGradient = this.maxValue / (this.colorStops.length - 1);

        for (i = 0; i < this.colorStops.length - 1; i++) {
          percentIncrease = 100 / stepsPerGradient / 100;

          firstColor = this.colorStops[i];
          targetColor = this.colorStops[i + 1];

          firstColorDecArray = this.tools.parseColor(firstColor);
          targetColorDecArray = this.tools.parseColor(targetColor);

          for (j = 0; j <= stepsPerGradient; j++) {
            if (j == 0) {
              result.push(firstColor);
            } else if (j == stepsPerGradient) {
              result.push(targetColor);
            } else {
              stepColorDecArray = [firstColorDecArray[0] + (percentIncrease * j) * (targetColorDecArray[0] - firstColorDecArray[0]),
                firstColorDecArray[1] + (percentIncrease * j) * (targetColorDecArray[1] - firstColorDecArray[1]),
                firstColorDecArray[2] + (percentIncrease * j) * (targetColorDecArray[2] - firstColorDecArray[2])
              ];
              result.push(this.tools.decimalToHex(stepColorDecArray));
            }
          }
        }

        return result;
      },
      tools: {
        parseColor: function(hexColorString) {
          var m;
          m = hexColorString.match(/^#([0-9a-f]{6})$/i)[1];
          if (m) {
            return [parseInt(m.substring(0, 2), 16), parseInt(m.substring(2, 4), 16), parseInt(m.substring(4, 6), 16)];
          }
        },
        decimalToHex: function(decimalNumberArray) {
          //TODO fikse tall under ti - alltid to plasser
          var results = [];

          results[1] = Math.round(decimalNumberArray[0]).toString(16);
          results[2] = Math.round(decimalNumberArray[1]).toString(16);
          results[3] = Math.round(decimalNumberArray[2]).toString(16);

          for (var i = 1; i <= results.length; i++) {
            if (!(isNaN(results[i]))) {
              if (results[i] < 10) {
                results[i] = "0" + results[i];
              }
            }
          }

          return "#" + results[1] + results[2] + results[3];
        }
      }
    }

		//get the canvas element
		var canvasElm = document.querySelector("canvas");
		//initialize the slider
		gradientSlider.init(canvasElm);
<canvas id="gradient-slider" width="600" height="200" class="gradientslider"></canvas>

最佳答案

我的解决方案是函数tools.decimalToHex的固定版本。错误在于您将结果数组视为数字数组,而不是字符串数组。

    decimalToHex : function(decimalNumberArray){
        var results = [];

        // Maybe check if number is in range 0 - 255, before converting to string?
        results[0] = Math.round(decimalNumberArray[0]).toString(16);
        results[1] = Math.round(decimalNumberArray[1]).toString(16);
        results[2] = Math.round(decimalNumberArray[2]).toString(16);

        for (var i = 0; i<results.length; i++) {
                if(results[i].length < 2) {
                    results[i] = "0" + results[i];
                }
        }

        return "#" + results[0] + results[1] + results[2];
    }

对应的jsFiddle:https://jsfiddle.net/8xr4zujj/4/

关于javascript - canvas 的 javascript 中的自定义渐变有一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37387611/

相关文章:

javascript - underscore.js debounce 函数中的内部函数上下文

javascript - 打印图案的功能

javascript - Polymer 1.0 使用 ExcludeLocalNames 跳过节点

html - 仅在具有相对属性的 div 中右对齐元素

javascript - 为什么我的键码测试在 Canvas 游戏中给我未定义?

javascript - 在 url 中使用 # 打开 html div 元素

javascript - 错误回调不适用于 React Native 中的地理定位

html - p 标签在满之前换行

CSS 未在 Facebook Canvas 页面中加载

javascript 球在 html Canvas 中弹跳