export default class GenerateCanvas {
canvasWidth = 314
canvasHeight = 376
canvas = null
context = null
constructor(node) {
this.canvas = node
this.context = this.canvas.getContext('2d')
this.resizeCanvas()
}
resizeCanvas() {
const dpr = uni.getSystemInfoSync().pixelRatio
this.canvas.width = this.canvasWidth * dpr
this.canvas.height = this.canvasHeight * dpr
this.context.scale(dpr, dpr)
}
drawText(text, x, y, options = {}) {
this.context.font = `${options.fontWeight || ''} ${options.fontSize}px cursive`
this.context.fillStyle = options.color || '#2A2A2A'
this.context.textAlign = options.textAlign || 'start'
this.context.textBaseline = options.textBaseline || 'hanging'
this.context.fillText(text, x, y)
}
drawRotateText(text, x, y, options = {}) {
this.context.save()
const width = this.context.measureText(text).width
this.context.translate(x + options.fontSize / 2, y)
this.context.rotate((90 * Math.PI) / 180)
this.drawText(text, 0, 0, options)
this.context.restore()
}
drawLineFeedText(text, chunkSize, x, y, gap, options = {}) {
const splitText = this.splitString(text, chunkSize)
splitText.forEach((text) => {
this.drawText(text, x, (y += gap), options)
})
}
splitString(str, size) {
const chunks = []
for (let i = 0; i < str.length; i += size) {
const chunk = str.substring(i, i + size)
chunks.push(chunk)
}
return chunks
}
drawLine(startPoint, endPoint) {
const [sx, sy] = startPoint
const [ex, ey] = endPoint
this.context.beginPath()
this.context.strokeStyle = '#A79F88'
this.context.lineWidth = 0.5
this.context.moveTo(sx, sy)
this.context.lineTo(ex, ey)
this.context.stroke()
this.context.closePath()
}
drawImage(imagePath, x, y, width, height, radius = 0) {
this.createImage(imagePath).then((image) => {
this.drawWithOptionalClip(image, x, y, width, height, radius)
})
}
drawPattern(imagePath) {
this.createImage(imagePath).then((image) => {
const pattern = this.context.createPattern(image, 'no-repeat')
this.drawRect(0, 0, this.canvasWidth, this.canvasHeight, pattern)
})
}
createImage(path) {
return new Promise((resolve, reject) => {
const image = this.canvas.createImage()
image.src = path
image.onload = () => {
resolve(image)
}
})
}
drawWithOptionalClip(imagePath, x, y, width, height, radius = 0) {
if (radius > 0) {
this.context.save()
this.context.beginPath()
this.context.arc(x + width / 2, y + height / 2, radius, 0, 2 * Math.PI)
this.context.clip()
}
this.context.drawImage(imagePath, x, y, width, height)
if (radius > 0) {
this.context.restore()
}
}
drawRect(x, y, width, height, color = '#A79F88') {
this.context.fillStyle = color
this.context.fillRect(x, y, width, height)
}
}