sindresorhus/eslint-plugin-unicorn

Rule proposal: `prefer-path2d`

Closed

#1,272 opened on May 13, 2021

 (2 comments) (1 reaction) (0 assignees)JavaScript (468 forks)user submission
help wantednew rule

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

Before Path2D was added, when doing animation with lots of CanvasRenderingContext2D draw methods, we have to put in a function and call it again and again. But Path2D can be reused, it should be recommanded.

Fail

function draw() {
	context.moveTo(220, 60);
	context.arc(170, 60, 50, 0, 2 * Math.PI);
	// ...
	context.stroke();
}

function step() {
	draw();
	if (foo) {
		requestAnimationFrame(step);
	}
}

requestionAnimationFrame(step)

Pass

const path = new Path2D();
path.moveTo(220, 60);
path.arc(170, 60, 50, 0, 2 * Math.PI);

function step() {
	context.stroke(path);
	if (foo) {
		requestAnimationFrame(step);
	}
}

requestionAnimationFrame(step)

Not sure if it's doable in ESLint, maybe we can check a function called many CanvasRenderingContext2D draw method without variables, and suggest Path2D.

Contributor guide