Last active
August 6, 2019 08:13
-
-
Save OEvgeny/9ba20a48ca890d6b5086f3a5bc4865d0 to your computer and use it in GitHub Desktop.
Draw Square Spin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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