Created
April 4, 2020 17:11
-
-
Save wan2land/024df2e68a1bb32ba684b41d8be595ed to your computer and use it in GitHub Desktop.
This file contains 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 applyStrokeOptions(ctx, options = {}) { | |
ctx.setLineDash(options.dash || []) | |
ctx.lineWidth = options.width || 1 | |
ctx.strokeStyle = options.color || '#000000' | |
} | |
function applyFillOptions(ctx, options = {}) { | |
ctx.fillStyle = options.color || '#000000' | |
} | |
export function lines(points) { | |
return { | |
stroke(ctx, options) { | |
if (points.length < 1) { | |
return | |
} | |
applyStrokeOptions(ctx, options) | |
ctx.beginPath() | |
ctx.moveTo(points[0].x, points[0].y) | |
for (const point of points.slice(1)) { | |
ctx.lineTo(point.x, point.y) | |
} | |
ctx.stroke() | |
}, | |
fill(ctx, options) { | |
if (points.length < 1) { | |
return | |
} | |
applyFillOptions(ctx, options) | |
ctx.beginPath() | |
ctx.moveTo(points[0].x, points[0].y) | |
for (const point of points.slice(1)) { | |
ctx.lineTo(point.x, point.y) | |
} | |
ctx.fill() | |
}, | |
} | |
} | |
export function polygon(points) { | |
return { | |
stroke(ctx, options) { | |
if (points.length < 1) { | |
return | |
} | |
applyStrokeOptions(ctx, options) | |
ctx.beginPath() | |
ctx.moveTo(points[points.length - 1].x, points[points.length - 1].y) | |
for (const point of points) { | |
ctx.lineTo(point.x, point.y) | |
} | |
ctx.stroke() | |
}, | |
fill(ctx, options) { | |
if (points.length < 1) { | |
return | |
} | |
applyFillOptions(ctx, options) | |
ctx.beginPath() | |
ctx.moveTo(points[points.length - 1].x, points[points.length - 1].y) | |
for (const point of points) { | |
ctx.lineTo(point.x, point.y) | |
} | |
ctx.fill() | |
}, | |
} | |
} | |
export function text(point, text) { | |
return { | |
fill(ctx, options = {}) { | |
ctx.fillStyle = options.color || '#000000' | |
ctx.font = options.font || '16px sans-serif' | |
ctx.textAlign = options.textAlign || 'left' | |
ctx.textBaseline = options.textBaseline || 'middle' | |
ctx.fillText(text, point.x, point.y) | |
}, | |
} | |
} | |
export function circle(point, radius) { | |
return { | |
stroke(ctx, options) { | |
applyStrokeOptions(ctx, options) | |
ctx.beginPath() | |
ctx.arc(point.x, point.y, radius, 0, 2 * Math.PI) | |
ctx.stroke() | |
}, | |
fill(ctx, options) { | |
applyFillOptions(ctx, options) | |
ctx.beginPath() | |
ctx.arc(point.x, point.y, radius, 0, 2 * Math.PI) | |
ctx.fill() | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment