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

ChartJS 文档中有一个关于模式和渐变的部分,它允许传递一个 CanvasPattern 或 CanvasGradient 对象而不是字符串颜色。
在这里阅读:
http://www.chartjs.org/docs/latest/general/colors.html
正如官方文档所说,只需将 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)
查看栏和全局选项,仅使用图表似乎不可能做到这一点。
http://www.chartjs.org/docs/#bar-chart-chart-options
http://www.chartjs.org/docs/#getting-started-global-chart-configuration
由于 Chartsjs 使用 canvas 元素来显示其元素,因此您也无法实现 CSS 解决方案。如果您确实想这样做,可以尝试编辑 Chartjs 库。或者只选择纯色。