export default { circleImg(ctx, img, x, y, w, h, r, state = true) { state && ctx.save() ctx.fillStyle = 'transparent' if (w < 2 * r) r = w / 2 if (h < 2 * r) r = h / 2 ctx.beginPath() ctx.moveTo(x + r, y) // 右上角 ctx.arcTo(x + w, y, x + w, y + h, r) ctx.arcTo(x + w, y + h, x, y + h, r) ctx.arcTo(x, y + h, x, y, r) ctx.arcTo(x, y, x + w, y, r) ctx.closePath() ctx.strokeStyle = 'transparent' ctx.stroke() ctx.clip() if (img) { ctx.drawImage(img, x, y, w, h) } state && ctx.restore() }, drawOneText(ctx, text, fontSize, color, canvasWidth, top) { ctx.font = fontSize ctx.fillStyle = color let strWidth = ctx.measureText(text).width ctx.fillText(text, (canvasWidth - strWidth) / 2, top) }, /** * 绘制多行文本 * @param str 文本内容 * @param initHeight 文本绘制的初始高度 * @param titleHeight 绘制文本的高度 */ drawText(ctx, str, font, color, top, lineHeight, canvasWidth, textWidth) { ctx.font = font ctx.fillStyle = color var lineWidth = 0 var lastSubStrIndex = 0 //每次开始截取的字符串的索引 for (let i = 0; i < str.length; i++) { lineWidth += ctx.measureText(str[i]).width if (lineWidth > textWidth) { ctx.fillText( str.substring(lastSubStrIndex, i), (canvasWidth - textWidth) / 2 + 5, top ) //绘制截取部分 top += lineHeight lineWidth = 0 lastSubStrIndex = i } if (i == str.length - 1) { //绘制剩余部分 ctx.fillText( str.substring(lastSubStrIndex, i + 1), (canvasWidth - lineWidth) / 2, top ) } } top = top + lineHeight return top } }