I have the following function that draws a canvas pattern. It works so slow when canvas size bigger then 512x512.
const defaultConfig: Divot = { step: 8, triangleWidth: 4, radius: 0.6, strokeStyle: '#000' };
export function DivotTemplate(divot: Partial<Divot> = defaultConfig, canvas: HTMLCanvasElement): HTMLCanvasElement {
const config = { ...defaultConfig, ...divot };
const { width, height } = canvas;
const { step, radius, strokeStyle, triangleWidth } = config;
const TAU = 2 * Math.PI;
let x = [1, 1, triangleWidth];
const y = [1, triangleWidth, triangleWidth / 2];
const context = canvas.getContext('2d');
if (!context) throw Error('Canvas context error');
context.strokeStyle = strokeStyle;
/* Рисуем три точки для первого треугольника */
for (let c = 0; c < height; c++) {
if (c % 2 === 0) {
x[0] = triangleWidth + 1;
x[1] = triangleWidth + 1;
x[2] = 1;
} else {
let s = step / 2;
x = [1 + s, 1 + s, triangleWidth + 1 + s];
}
for (let i = 0; i < width; i = i + step) {
context.beginPath();
context.arc(x[0], y[0], radius, 0, TAU);
context.stroke();
context.beginPath();
context.arc(x[1], y[1], radius, 0, TAU);
context.stroke();
context.beginPath();
context.arc(x[2], y[2], radius, 0, TAU);
context.stroke();
/* Соединяем две точки из трех */
context.beginPath();
context.moveTo(x[2], y[2]);
context.lineTo(x[0], y[0]);
context.stroke();
context.beginPath();
context.moveTo(x[2], y[2]);
context.lineTo(x[1], y[1]);
context.stroke();
x[0] = x[0] + step;
x[1] = x[1] + step;
x[2] = x[2] + step;
}
x = [1, 1, triangleWidth + 1];
y[0] = y[0] + step;
y[1] = y[1] + step;
y[2] = y[2] + step;
}
context.stroke();
return canvas;
}
As result I get a canvas pattern like:
I what can I optimize in this code according canvas and loops?
