2017-03-18 27 views
3

當我在全屏窗口中生成折線圖時,顯示的顏色位於聲明的半徑中,但是當我嘗試調整窗口大小時,圖表調整大小正確,但漸變顏色混亂。我試圖通過監聽器來解決這個問題,但它不起作用。Javascript - 帶響應漸變線填充的Chart.js

任何人有想法嗎?

這裏是我的代碼:

var chrt = document.getElementById("mycanvas"); 
var ctx = chrt.getContext("2d"); 
var gradient = ctx.createLinearGradient(300, 0, 300, 600); 
gradient.addColorStop(0, 'black'); 
gradient.addColorStop(0.25, 'red'); 
gradient.addColorStop(0.5, 'orange'); 
gradient.addColorStop(0.75, 'yellow'); 
gradient.addColorStop(1, 'green'); 
mycanvas.addEventListener("resize", gradient_declaration); 

function gradient_declaration() { 
    var w = mycanvas.innerWidth; 
    var h = mycanvas.innerHeight; 
    if (gradient) { gradient.destroy(); } else { 
     var gradient = ctx.createLinearGradient(w/2, 0, w/2, h); 
     gradient.addColorStop(0, 'black'); 
     gradient.addColorStop(0.25, 'red'); 
     gradient.addColorStop(0.5, 'orange'); 
     gradient.addColorStop(0.75, 'yellow'); 
     gradient.addColorStop(1, 'green'); 
    } 
} 

回答

3

它可能對你太晚了,但我遇到了同樣的問題來了。我解決它的方式是創建一個內聯插件,在每次佈局更改時重新計算梯度,例如(調整大小,數據更改等)

var chart2 = new Chart(ctx, { 
    plugins: [ 
    { 
     id: "responsiveGradient", 

     afterLayout: function(chart, options) { 
     var scales = chart.scales; 

     // create a linear gradient with the dimentions of the scale 
     var color = chart.ctx.createLinearGradient(
      scales["x-axis-0"].left, 
      scales["y-axis-0"].bottom, 
      scales["x-axis-0"].right, 
      scales["y-axis-0"].top 
     ); 
     // add gradients stops 
     color.addColorStop(0, "black"); 
     color.addColorStop(0.25, "red"); 
     color.addColorStop(0.5, "orange"); 
     color.addColorStop(0.75, "yellow"); 
     color.addColorStop(1, "green"); 
     // changes the background color option 
     chart.data.datasets[0].backgroundColor = color; 
     } 
    } 
    ] 
});