score:2
HTML Canvas' createLinearGradient()
depends on the y
axis coordinates that you pass in as argument. You had passed in a static 200 every time (i.e. ctx.createLinearGradient(0, 200, 0, 20);
).
That's why the gradient's steps remains the same everytime. For the gradient to update, you have to recalculate the height of the <canvas>
element on window resize and pass it in to createLinearGradient()
again.
You can accomplish this by:
- Separating the block where you create the gradient into a separate function.
eleHeight
retrieves the height of the canvas element.
generateGradient(){
let eleHeight = this.myChart.nativeElement.offsetHeight;
// console.log(eleHeight)
let purple_orange_gradient: CanvasGradient = this.myChart.nativeElement.getContext('2d').createLinearGradient(0, eleHeight, 0, 20);
purple_orange_gradient.addColorStop(0.1, "#000279");
purple_orange_gradient.addColorStop(0.2, "#0000F2");
purple_orange_gradient.addColorStop(0.3, "#0362FD");
purple_orange_gradient.addColorStop(0.4, "#04D3FD");
purple_orange_gradient.addColorStop(0.5, "#45FFB7");
purple_orange_gradient.addColorStop(0.6, "#B7FF46");
purple_orange_gradient.addColorStop(0.7, "#FFD401");
purple_orange_gradient.addColorStop(0.8, "#FE6500");
purple_orange_gradient.addColorStop(0.9, "#F30004");
purple_orange_gradient.addColorStop(1, "#7E0100");
return purple_orange_gradient;
}
- Add a onresize event handler to your containing
<div>
and generate the gradient again. You also need to programatically update the chart every time you make a change to re-render it.
<div style="display: block; max-height: 100%" (window:resize)="onResize($event)" >
...
</div>
onResize(event?){
// console.log("onResize");
this.barChartData.forEach((d, i) => {
d.backgroundColor = this.generateGradient();
})
this.chart.chart.update(); //update the chart to re-render it
}
- Update the
barchartData
's properties (that uses gradient) inngAfterViewInit
. We need to do this here because we only want the height of the<canvas>
element with data populated. Without data populated, the element is much smaller.
ngAfterViewInit(){
this.barChartData.forEach((d, i) => {
d.backgroundColor = this.generateGradient();
});
this.chart.chart.update(); //update the chart to re-render it
}
Have a look at this Stackblitz example⚡⚡ I have created.
score:1
You have to change the gradient whenever your canvas is resizing. Took me a while to figure out a good structure to minimize lines of code and optimize performance. This is the best I could achieve.
There are exeptions when the chart.js
onResize()
fires though but I couldn't solve this issue completly bulletproof. But for simple resizes it should work.
Complete code (same code in JSBin with live preview):
let sData = {}
sData.labels = []
sData.data = []
const count = 50
for (let x = 0; x < count; x++) {
sData.data.push(Math.floor(Math.random()*100))
sData.labels.push(x)
}
const canvas = document.getElementById('chart')
const ctx = canvas.getContext("2d")
let purple_orange_gradient
function updateGradient() {
let bottom = bar_chart.chartArea.bottom
let top = bar_chart.chartArea.top
purple_orange_gradient = ctx.createLinearGradient(0, bottom+top, 0, top)
purple_orange_gradient.addColorStop(0.1, "#000279")
purple_orange_gradient.addColorStop(0.2, "#0000F2")
purple_orange_gradient.addColorStop(0.3, "#0362FD")
purple_orange_gradient.addColorStop(0.4, "#04D3FD")
purple_orange_gradient.addColorStop(0.5, "#45FFB7")
purple_orange_gradient.addColorStop(0.6, "#B7FF46")
purple_orange_gradient.addColorStop(0.7, "#FFD401")
purple_orange_gradient.addColorStop(0.8, "#FE6500")
purple_orange_gradient.addColorStop(0.9, "#F30004")
purple_orange_gradient.addColorStop(1.0, "#7E0100")
return purple_orange_gradient
}
const bar_chart = new Chart(ctx, {
type: "horizontalBar",
data: {
labels: sData.labels,
datasets: [{
borderColor: purple_orange_gradient,
pointBorderColor: purple_orange_gradient,
pointBackgroundColor: purple_orange_gradient,
pointHoverBackgroundColor: purple_orange_gradient,
pointHoverBorderColor: purple_orange_gradient,
pointBorderWidth: 10,
pointHoverRadius: 10,
pointHoverBorderWidth: 1,
pointRadius: 3,
fill: true,
backgroundColor: purple_orange_gradient,
borderWidth: 4,
data: sData.data
}]
},
options: {
legend: {
display: false,
position: "bottom"
},
scales: {
yAxes: [{
ticks: {
display: false,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold",
beginAtZero: true,
maxTicksLimit: 1,
padding: 20,
},
gridLines: {
drawTicks: false,
display: false
}
}],
xAxes: [{
gridLines: {
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
beginAtZero: true,
fontColor: "rgba(0,0,0,0.5)",
fontStyle: "bold"
}
}]
},
onResize: function(chart, size) {
// onResize gradient change
changeGradient()
}
}
});
// Initial gradient change
changeGradient()
function changeGradient() {
let newGradient = updateGradient()
bar_chart.data.datasets[0].borderColor = newGradient
bar_chart.data.datasets[0].pointBorderColor = newGradient
bar_chart.data.datasets[0].pointBackgroundColor = newGradient
bar_chart.data.datasets[0].pointHoverBackgroundColor = newGradient
bar_chart.data.datasets[0].pointHoverBorderColor = newGradient
bar_chart.data.datasets[0].backgroundColor = newGradient
bar_chart.update()
}
Source: stackoverflow.com
Related Query
- How to maintain chartjs / ng2-charts gradient on window resize?
- how to get React chartjs to resize back down with window
- How to modify bar width in Chartjs 2 bar charts
- ChartJS Doughnut Charts Gradient Fill
- ChartJS won't draw graph inside bootstrap tab until window resize
- How do I make line charts overlay over bar charts in chartjs
- How to add ChartJS code in Html2Pdf to view image
- How do I add time sourced from an external source as an X axis to a ChartJS graph?
- chartjs - how to set the order in which the different charts are displayed
- How can I load multiple Chartjs charts with different data on the same page?
- How to generate chartjs charts to pdf using laravel?
- When I added a funnel chart to chartjs all the charts are load compressed until resize page
- How to change position from absolute to relative in charts in ChartJS
- How to add left padding for my charts done in ChartJs and my Google Map so it is not glued to the limit of the page on the left
- how to change thickness of two doughnut charts in chartjs
- How to 1. pass two datasets and 2.have permanent label on charts in Chartjs
- How to resize chartjs in bootstrap columns for different browsers
- Chart.js how to change point radius of scatter charts on resize events?
- How to extend chartjs line charts in ReactJS to show solid and dashed line together?
- How to run Chart.js samples using source code
- how to not repeat code while creating multiple charts in chart js
- How do I make many ChartJS charts on the same page to have the same height and also even column width?
- ChartJS Line Charts - remove color underneath lines
- How to set ChartJS Y axis title?
- How to disable chartjs legendclick
- how to change size of point in ChartJS
- How to disable a tooltip for a specific dataset in ChartJS
- How to modify chartjs tooltip so i can add customized strings in tooltips
- ChartJs 2.0 How do I obtain point information being clicked upon?
- how to plot multiple time series in chartjs where each time series has different times
More Query from same tag
- Chart.js 2.0 - How to change default appearance of canvas/chart elements
- Chart js - Get bar width after render
- Laravel PDF generation with Graph and send it with Email
- chart.js with json data and jquery - error :-(
- Chart.js Bar chart : display labels
- How to get data on chart based on selected date (Filtering data Chart JS with datepicker)
- chart.js 2.7.1 - polar area chart has too much padding
- Scatter chart in chart.js
- chartjs - bar graphs size not increasing
- How to assign a logarithmic scale to y axis in chart.js?
- Programmatically creating labels for Chart.js in angular?
- How to make bars different colours in Chart.js with csv data?
- Why isn't my X axes on my bar chart starting from zero?
- How to get the bands to implement in Chart.js the band extension?
- How to have chart.js automatically build x-axis labels based on x,y dataset?
- Reanimate Data Values in CharJS
- Chart.js showing old chart on hover
- angular-chart.js doughnut chart : How do I change width of the arc of a doughnut?
- How can I add background color of length bars in chart (chartJS)?
- How does chart updating works within the context of react?
- How to disable Chart JS tooltip when there is no value?
- Chartjs with streaming plugin: update y-range
- Create space between legend and chart in charts.js
- Destroying the Div and its contents inside the jquery dialog when close button is clicked
- Dynamically Creating Json Array Javascript
- Style individual points from one dataset in Chart.js
- Stepped line with null values in chart.js
- Chartjs doesn't update dataset label on tooltips
- Rendering a chart.js component twice in a page
- Chart.js: Can datasets be overlaid in a bar chart? (Not the same as stacked)