Skip to content

Instantly share code, notes, and snippets.

@OEvgeny
Last active August 6, 2019 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OEvgeny/9ba20a48ca890d6b5086f3a5bc4865d0 to your computer and use it in GitHub Desktop.
Save OEvgeny/9ba20a48ca890d6b5086f3a5bc4865d0 to your computer and use it in GitHub Desktop.
Draw Square Spin
function makeSquereSpin(spinRadius, segmentCount = 10, center = [0, 0]) {
const points = [center];
const segmentLength = spinRadius * 2;
let currentPoint = [...center];
let currentRadius = 0;
for (let i = 0; i < segmentCount; i++) {
const currentLength = segmentLength + currentRadius;
currentRadius += segmentLength;
let deviation;
const phase = i % 4
if (phase === 0) { deviation = [0, -currentLength] }
else if (phase === 1) { deviation = [currentLength, 0] }
else if (phase === 2) { deviation = [0, currentLength] }
else if (phase === 3) { deviation = [-currentLength, 0] }
currentPoint[0] += deviation[0];
currentPoint[1] += deviation[1];
points.push([...currentPoint]);
}
return points;
}
const canvasSize = 512; // px
function drawSpin(spinRadius, segmentCount = 10) {
const spinPoints = makeSquereSpin(spinRadius, segmentCount, [canvasSize / 2, canvasSize / 2]);
const canvas = document.createElement('canvas');
canvas.width = canvasSize;
canvas.height = canvasSize;
const context = canvas.getContext('2d');
context.fillStyle = "green";
context.fillRect(0, 0, canvasSize, canvasSize);
let prevPoint = spinPoints.shift();
context.beginPath();
for (const point of spinPoints) {
context.moveTo(...prevPoint);
context.lineTo(...point);
prevPoint = point;
}
context.stroke();
const url = canvas.toDataURL();
return url;
}
drawSpin(3, 15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment