function createPattern()

in packages/charts/src/chart_types/xy_chart/utils/texture.ts [39:91]


function createPattern(
  ctx: CanvasRenderingContext2D,
  dpi: number,
  patternCanvas: HTMLCanvasElement,
  baseColor: Color | ColorVariant,
  sharedGeometryOpacity: Ratio,
  textureStyle?: TexturedStyles,
): CanvasPattern | null {
  const pCtx = patternCanvas.getContext('2d');
  if (!textureStyle || !pCtx) return null;

  const { size = 10, stroke, strokeWidth = 1, opacity, shapeRotation, fill, dash } = textureStyle;

  const spacing = getSpacing(textureStyle);
  const cssWidth = size + spacing.x;
  const cssHeight = size + spacing.y;
  patternCanvas.width = dpi * cssWidth;
  patternCanvas.height = dpi * cssHeight;

  pCtx.globalAlpha = sharedGeometryOpacity * (opacity ?? 1);
  pCtx.lineWidth = strokeWidth;

  pCtx.strokeStyle = getColorFromVariant(baseColor, stroke ?? ColorVariant.Series);
  if (dash) pCtx.setLineDash(dash);

  if (fill) pCtx.fillStyle = getColorFromVariant(baseColor, fill);

  const [path, pathRotation] = getPath(textureStyle, size, strokeWidth);
  const itemRotation = (shapeRotation ?? 0) + pathRotation;

  pCtx.scale(dpi, dpi);
  pCtx.translate(cssWidth / 2, cssHeight / 2);

  if (itemRotation) pCtx.rotate(degToRad(itemRotation));

  pCtx.beginPath();

  if (path) {
    pCtx.stroke(path);
    if (fill) pCtx.fill(path);
  }

  const pattern = ctx.createPattern(patternCanvas, 'repeat')!; // HTMLCanvasElement always yields a CanvasPattern anyway

  const { offset, rotation } = textureStyle;
  const matrix = new DOMMatrix([1 / dpi, 0, 0, 1 / dpi, 0, 0]);
  if (offset?.global) matrix.translateSelf(offset.x ?? 0, offset.y ?? 0);
  matrix.rotateSelf(rotation ?? 0);
  if (offset && !offset.global) matrix.translateSelf(offset.x ?? 0, offset.y ?? 0);

  pattern.setTransform(matrix);
  return pattern;
}