0

I'm currently drawing a line chart with the following code in HTML canvas:

var data   = [0, 10, 40, 30, 40, 10, 0]
var labels = ['10-08', '10-09', '10-10', '10-11', '10-12', '10-13', '10-14']

var canvas = document.getElementById('chart02')

if(screen.width/4 < 480) canvas.width = 0.90*canvas.parentNode.clientWidth
else                     canvas.width = 0.25*screen.width
canvas.height = canvas.width * 1080/1920
var dx        = canvas.width / (data.length-1)

var min_y = Math.min(...data)
var max_y = Math.max(...data)
var dy    = (canvas.height-0)/(max_y-min_y)
for(var i=0; i<data.length; ++i)
  data[i] = canvas.height - data[i]*dy

var ctx       = canvas.getContext('2d')
ctx.lineWidth = 2
ctx.fillStyle = '#0088ff';  // rgba
ctx.beginPath()
ctx.moveTo(0*dx, data[0])
for(var i=1; i < data.length-2; ++i){
  var xc = ( dx*(i+0) +  dx*(i+1)) / 2  // midpoint
  var yc = (data[i+0] + data[i+1]) / 2  // midpoint
  ctx.quadraticCurveTo(i*dx, data[i], xc, yc)
}
ctx.quadraticCurveTo((i+0)*dx, data[i+0], (i+1)*dx, data[i+1])  // curve through the last two points
ctx.strokeStyle = '#3341ff'
ctx.stroke()

ctx.font      = '1em Times New Roman';
ctx.fillStyle = '#2a3f58';  // rgba
for(var i=0; i<data.length; ++i)
  ctx.fillText(labels[i],  i*dx,canvas.height)
<canvas id="chart02"></canvas>

Now I want to color the line with a gradient that extends "outward", to replicate the following effect:

enter image description here

(It'd also be cool to have a smoothly-varying linewidth too.)

This answer draws a gradient but in the other direction.

How can I draw a gradient like the one in the image?

lupz
  • 3,406
  • 2
  • 27
  • 41
étale-cohomology
  • 1,765
  • 1
  • 22
  • 27
  • 1
    Does this answer your question? [Gradient Stroke Along Curve in Canvas](https://stackoverflow.com/questions/24027087/gradient-stroke-along-curve-in-canvas) – lupz Oct 18 '21 at 08:36

0 Answers0