Point Style property with Inverted Image in Line Chart.js

北慕城南 提交于 2021-02-08 07:02:52

问题


Refer the fiddle URL : https://jsfiddle.net/vL0ta76w/

Current Behaviour Point Style Property in Chart.js provides certain icons like a circle, triangle, rect, etc. to be displayed on the line chart

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
	    {
	      label: '# of Votes',
	      data: [12, -19, 3, 5, 2, 3],
      	borderWidth: 1,
        pointStyle:'triangle',
        pointRadius:'10',
        pointBackgroundColor:'red'
    	},	
		
		],
   pointStyle:'triangle'
  },
  options: {
  	scales: {
    	yAxes: [{
        ticks: {
					reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas { background-color : #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

Expected Result:

However is it possible to display an inverted triangle? Any property to display an inverted triangle or any custom image that can be inserted Through the method, I can manage to change color if the dataset has negative value. but facing issue while showing the image as inverted or rotated 180 degrees


回答1:


Chart js allows an array of pointStyles to be supplied instead of just 1. It also allows images to be supplied in place of a preset pointer style.

var image = document.getElementById('source');
var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, -19, 3, 5, 2, 3],
        borderWidth: 1,
        pointStyle: ['triangle', image, 'triangle', 'triangle', 'triangle', 'triangle'],
        pointRadius: '10',
        pointBackgroundColor: 'red'
      },

    ],
    pointStyle: 'triangle'
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<div style="display:none;">
  <img id="source" src="https://image.flaticon.com/icons/png/128/25/25224.png">
</div>

To then make this dynamic you could map the data in the datset to produce the pointerStyle array

let pointerStyles = [12,-19,2,3,4].map(value=>{
 return value >=0 ? 'triangle' : 'other-triangle'
});

console.log(pointerStyles);


来源:https://stackoverflow.com/questions/52474546/point-style-property-with-inverted-image-in-line-chart-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!