]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
Enable applying of gradients and pattern on line segments (#11217)
authorstockiNail <stocki.nail@gmail.com>
Thu, 27 Apr 2023 22:25:13 +0000 (00:25 +0200)
committerGitHub <noreply@github.com>
Thu, 27 Apr 2023 22:25:13 +0000 (18:25 -0400)
* Enable applying of gradients and pattern on line segments

* add test case

* improve replacer

src/helpers/helpers.segment.js
test/fixtures/controller.line/segments/gradient.js [new file with mode: 0644]
test/fixtures/controller.line/segments/gradient.png [new file with mode: 0644]

index 0c6dbfd0ce2dab89dd372b652f7d5b1922c04589..50ea8da5bc8035a0c4c51c1e5df6d032938ed957 100644 (file)
@@ -1,5 +1,6 @@
 import {_angleBetween, _angleDiff, _isBetween, _normalizeAngle} from './helpers.math.js';
 import {createContext} from './helpers.options.js';
+import {isPatternOrGradient} from './helpers.color.js';
 
 /**
  * @typedef { import('../elements/element.line.js').default } LineElement
@@ -346,5 +347,18 @@ function readStyle(options) {
 }
 
 function styleChanged(style, prevStyle) {
-  return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle);
+  if (!prevStyle) {
+    return false;
+  }
+  const cache = [];
+  const replacer = function(key, value) {
+    if (!isPatternOrGradient(value)) {
+      return value;
+    }
+    if (!cache.includes(value)) {
+      cache.push(value);
+    }
+    return cache.indexOf(value);
+  };
+  return JSON.stringify(style, replacer) !== JSON.stringify(prevStyle, replacer);
 }
diff --git a/test/fixtures/controller.line/segments/gradient.js b/test/fixtures/controller.line/segments/gradient.js
new file mode 100644 (file)
index 0000000..8a09503
--- /dev/null
@@ -0,0 +1,34 @@
+const getGradient = (context) => {
+  const {chart, p0, p1} = context;
+  const ctx = chart.ctx;
+  const {x: x0} = p0.getProps(['x'], true);
+  const {x: x1} = p1.getProps(['x'], true);
+  const gradient = ctx.createLinearGradient(x0, 0, x1, 0);
+  gradient.addColorStop(0, p0.options.backgroundColor);
+  gradient.addColorStop(1, p1.options.backgroundColor);
+  return gradient;
+};
+
+module.exports = {
+  config: {
+    type: 'line',
+    data: {
+      datasets: [{
+        data: [{x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2}, {x: 3, y: 3}, {x: 4, y: 4}, {x: 5, y: 5}, {x: 6, y: 6}],
+        pointBackgroundColor: ['red', 'yellow', 'green', 'green', 'blue', 'pink', 'blue'],
+        pointBorderWidth: 0,
+        pointRadius: 10,
+        borderWidth: 5,
+        segment: {
+          borderColor: getGradient,
+        }
+      }]
+    },
+    options: {
+      scales: {
+        x: {type: 'linear', display: false},
+        y: {display: false}
+      }
+    }
+  }
+};
diff --git a/test/fixtures/controller.line/segments/gradient.png b/test/fixtures/controller.line/segments/gradient.png
new file mode 100644 (file)
index 0000000..74bdef2
Binary files /dev/null and b/test/fixtures/controller.line/segments/gradient.png differ