Created
November 11, 2019 23:37
-
-
Save alex-taxiera/65138d86a904e3909367de7ca07a1f96 to your computer and use it in GitHub Desktop.
A front end canvas manager
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
import Upload from './Upload.js' | |
export default class Artist { | |
constructor (canvas) { | |
this.canvas = canvas | |
this.ctx = canvas.getContext('2d') | |
} | |
getLink () { | |
return this.canvas.toDataURL() | |
} | |
reset () { | |
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height) | |
} | |
setColor (color) { | |
this.ctx.fillStyle = color | |
} | |
/** | |
* Set the scale to draw at. | |
* @param {Number[]} scale The x and y scale multipliers. | |
* @returns {Number[]} The updated scale value. | |
*/ | |
setScale (scale) { | |
this.ctx.scale(...scale.map((scale) => scale / 100)) | |
// FIXME: Currently we just return the updates scale based on the x value, instead of x and y | |
return scale[0] / 100 | |
} | |
resetScale (scale) { | |
this.ctx.scale(...scale.map((scale) => 100 / scale)) | |
} | |
fillRectangle (points, color) { | |
this.setColor(color) | |
this.ctx.fillRect(...points) | |
} | |
fixScale (scale) { | |
return scale / 100 | |
} | |
returnScale (decimal) { | |
return decimal * 100 | |
} | |
draw (data) { | |
const { | |
shapes, | |
settings = {} | |
} = data | |
let { | |
image, | |
scale, | |
offset, | |
path, | |
color | |
} = settings | |
if (shapes) return shapes.forEach(this.draw.bind(this)) | |
const adjustedScale = this.setScale(scale) | |
// TODO figure out height and width of layer?, subtract offset by half | |
offset = offset.map((offset) => offset * 1 / adjustedScale) | |
if (image !== undefined) this.drawImage(image, offset, data instanceof Upload) | |
else this.drawAndFill(path, color, offset) | |
this.resetScale(scale) | |
} | |
drawImage (image, offset = [0, 0], isUpload) { | |
if (isUpload) offset = [offset[0] - (image.width / 2), offset[1] - (image.height / 2)] | |
if (image) this.ctx.drawImage(image, ...offset) | |
} | |
drawAndFill (path, color, offset) { | |
path = path.map((point) => point.map((x, i) => x + offset[i])) | |
this.ctx.beginPath() | |
this.ctx.moveTo(...path[0]) | |
for (let i = 1; i < path.length; i++) { | |
this.ctx.lineTo(...path[i]) | |
} | |
this.ctx.lineTo(...path[0]) | |
this.ctx.closePath() | |
this.setColor(color) | |
this.ctx.fill() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment