用斜条纹或其他图案填充 Chart.js 条形图

Fer*_*oza 4 javascript chart.js

我正在尝试用条纹填充条形图,使其看起来像附加的图像。有没有办法做到这一点?其他图案呢?

带图案背景的图表

小智 6

老问题,但现在有模式附加组件:-)

https://github.com/ashiguruma/patternomaly

它包含 21 个可以在 chart.js 中使用的预定义模式。


rep*_*ept 5

ChartJS 文档中有一个关于模式和渐变的部分,它允许传递一个 CanvasPattern 或 CanvasGradient 对象而不是字符串颜色。

在这里阅读:

http://www.chartjs.org/docs/latest/general/colors.html


tot*_*dli 5

tl;博士

正如官方文档所说,只需将 aCanvasPattern或传递CanvasGradient给数据集的backgroundColor属性。

对不起,什么?

这可以通过像patternomaly这样的 3rd 方库来完成,但是如果您只想要一些简单的图案,则没有必要,因为您可以轻松创建一个自定义函数,该函数采用颜色并返回画布图案:

function createDiagonalPattern(color = 'black') {
  // create a 10x10 px canvas for the pattern's base shape
  let shape = document.createElement('canvas')
  shape.width = 10
  shape.height = 10
  // get the context for drawing
  let c = shape.getContext('2d')
  // draw 1st line of the shape 
  c.strokeStyle = color
  c.beginPath()
  c.moveTo(2, 0)
  c.lineTo(10, 8)
  c.stroke()
  // draw 2nd line of the shape 
  c.beginPath()
  c.moveTo(0, 8)
  c.lineTo(2, 10)
  c.stroke()
  // create the pattern from the shape
  return c.createPattern(shape, 'repeat')
}
Run Code Online (Sandbox Code Playgroud)

然后只需在您的数据集中调用它(如果需要,请不要忘记添加边框):

datasets: [{
  label: 'Good questions',
  data: [3, 4, 1, 6, 10],
  backgroundColor: createDiagonalPattern('green'),
  // create a border with the same color
  borderColor: 'green',
  borderWidth: 1,
}],
Run Code Online (Sandbox Code Playgroud)

边缘情况

请记住,画布具有抗锯齿功能,因此当您在拐角处绘制东西时,它可能会弄乱您的图案。为了缓解这种情况,只需从边缘绘制线条即可。

如果您像这样在角之间创建对角线:

c.beginPath()
c.moveTo(0, 0)
c.lineTo(10, 10)
c.stroke()
Run Code Online (Sandbox Code Playgroud)

那么图案看起来就不会无缝了,因为边角部分会被剪掉,所以你失去了无限的效果:

画布抗锯齿弄乱对角线

演示

function createDiagonalPattern(color = 'black') {
  // create a 10x10 px canvas for the pattern's base shape
  let shape = document.createElement('canvas')
  shape.width = 10
  shape.height = 10
  // get the context for drawing
  let c = shape.getContext('2d')
  // draw 1st line of the shape 
  c.strokeStyle = color
  c.beginPath()
  c.moveTo(2, 0)
  c.lineTo(10, 8)
  c.stroke()
  // draw 2nd line of the shape 
  c.beginPath()
  c.moveTo(0, 8)
  c.lineTo(2, 10)
  c.stroke()
  // create the pattern from the shape
  return c.createPattern(shape, 'repeat')
}
Run Code Online (Sandbox Code Playgroud)
datasets: [{
  label: 'Good questions',
  data: [3, 4, 1, 6, 10],
  backgroundColor: createDiagonalPattern('green'),
  // create a border with the same color
  borderColor: 'green',
  borderWidth: 1,
}],
Run Code Online (Sandbox Code Playgroud)

  • 赞成提供可用的答案而不仅仅是链接(并不是说链接没有用) (2认同)

Tui*_*noe 0

查看栏和全局选项,仅使用图表似乎不可能做到这一点。

http://www.chartjs.org/docs/#bar-chart-chart-options

http://www.chartjs.org/docs/#getting-started-global-chart-configuration

由于 Chartsjs 使用 canvas 元素来显示其元素,因此您也无法实现 CSS 解决方案。如果您确实想这样做,可以尝试编辑 Chartjs 库。或者只选择纯色。