gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:35:57 26 4
gpt4 key购买 nike

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

最佳答案

tl;博士
只需通过 CanvasPatternCanvasGradient到数据集的 backgroundColor属性为 official docs say .
对不起,什么?
这可以通过像 patternomaly 这样的第三方库来完成。 ,但如果您只想要一些简单的图案,则没有必要,因为您可以轻松创建一个自定义函数,该函数采用颜色并返回 Canvas 图案:

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')
}
然后只需在您的数据集中调用它(如果需要,请不要忘记添加边框):
datasets: [{
label: 'Good questions',
data: [3, 4, 1, 6, 10],
backgroundColor: createDiagonalPattern('green'),
// create a border with the same color
borderColor: 'green',
borderWidth: 1,
}],
边缘案例
请记住, Canvas 具有抗锯齿功能,因此当您在拐 Angular 处绘制东西时,它可能会弄乱您的图案。为了减轻这种情况,只需从边缘画线。
如果您像这样在拐 Angular 之间创建对 Angular 线:
c.beginPath()
c.moveTo(0, 0)
c.lineTo(10, 10)
c.stroke()
那么图案看起来就不是无缝的,因为 Angular 落会裁剪掉部分,所以你会失去无限的效果:
canvas anti-aliasing messing up diagonal lines
演示

var element = document.getElementById('chart');
var ctx = element.getContext("2d");

function createDiagonalPattern(color = 'black') {
let shape = document.createElement('canvas')
shape.width = 10
shape.height = 10
let c = shape.getContext('2d')
c.strokeStyle = color
c.beginPath()
c.moveTo(2, 0)
c.lineTo(10, 8)
c.stroke()
c.beginPath()
c.moveTo(0, 8)
c.lineTo(2, 10)
c.stroke()
return c.createPattern(shape, 'repeat')
}

var graph = new Chart(element, {
type: 'bar',
data: {
labels: ['jan', 'feb', 'mar', 'apr', 'may'],
datasets: [
{
label: 'Good questions',
data: [3, 4, 1, 6, 10],
backgroundColor: createDiagonalPattern('green'),
borderColor: 'green',
borderWidth: 1,
},
{
label: 'Bad questions',
data: [2, 7, 3, 5, 1],
backgroundColor: createDiagonalPattern('#FF0000'),
borderColor: '#FF0000',
borderWidth: 1,
},
],
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
}],
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="chart" ></canvas>

关于javascript - 用斜条纹或其他图案填充 Chart.js 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com