Linear Gradient

Linear Gradient - 图1

getGradient config setup actions

  1. let width, height, gradient;
  2. function getGradient(ctx, chartArea) {
  3. const chartWidth = chartArea.right - chartArea.left;
  4. const chartHeight = chartArea.bottom - chartArea.top;
  5. if (gradient === null || width !== chartWidth || height !== chartHeight) {
  6. // Create the gradient because this is either the first render
  7. // or the size of the chart has changed
  8. width = chartWidth;
  9. height = chartHeight;
  10. gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
  11. gradient.addColorStop(0, Utils.CHART_COLORS.blue);
  12. gradient.addColorStop(0.5, Utils.CHART_COLORS.yellow);
  13. gradient.addColorStop(1, Utils.CHART_COLORS.red);
  14. }
  15. return gradient;
  16. }
  1. const config = {
  2. type: 'line',
  3. data: data,
  4. options: {
  5. responsive: true,
  6. plugins: {
  7. legend: {
  8. position: 'top',
  9. },
  10. }
  11. },
  12. };
  1. const DATA_COUNT = 7;
  2. const NUMBER_CFG = {count: DATA_COUNT, min: -100, max: 100};
  3. const labels = Utils.months({count: 7});
  4. const data = {
  5. labels: labels,
  6. datasets: [
  7. {
  8. label: 'Dataset 1',
  9. data: Utils.numbers(NUMBER_CFG),
  10. borderColor: function(context) {
  11. const chart = context.chart;
  12. const {ctx, chartArea} = chart;
  13. if (!chartArea) {
  14. // This case happens on initial chart load
  15. return null;
  16. }
  17. return getGradient(ctx, chartArea);
  18. },
  19. },
  20. ]
  21. };
  1. const actions = [
  2. {
  3. name: 'Randomize',
  4. handler(chart) {
  5. chart.data.datasets.forEach(dataset => {
  6. dataset.data = Utils.numbers({count: chart.data.labels.length, min: -100, max: 100});
  7. });
  8. chart.update();
  9. }
  10. },
  11. {
  12. name: 'Add Data',
  13. handler(chart) {
  14. const data = chart.data;
  15. if (data.datasets.length > 0) {
  16. data.labels = Utils.months({count: data.labels.length + 1});
  17. for (var index = 0; index < data.datasets.length; ++index) {
  18. data.datasets[index].data.push(Utils.rand(-100, 100));
  19. }
  20. chart.update();
  21. }
  22. }
  23. },
  24. {
  25. name: 'Remove Data',
  26. handler(chart) {
  27. chart.data.labels.splice(-1, 1); // remove the label first
  28. chart.data.datasets.forEach(dataset => {
  29. dataset.data.pop();
  30. });
  31. chart.update();
  32. }
  33. }
  34. ];