Uniapp 微信小程序分享 - 自定义绘制分享图片

时间:2024-12-10 20:03:08
export const fillRoundRect = (ctx, x, y, width, height, radius, img) => { // console.log(ctx, x, y, width, height, radius, /*optional*/ fillColor) ctx.save(); ctx.translate(x, y); //绘制圆角矩形的各个边 drawRoundRectPath(ctx, width, height, radius); ctx.clip(); ctx.drawImage(img, 0, 0, width, height); // ctx.fillStyle = fillColor || "blue"; //若是给定了值就用给定的值否则给予默认值 // ctx.fill(); ctx.restore(); }; export const drawRoundRectPath = (ctx, width, height, radius) => { ctx.beginPath(0); //从右下角顺时针绘制,弧度从0到1/2PI ctx.arc(width - radius, height - radius, radius, 0, Math.PI / 2); //矩形下边线 ctx.lineTo(radius, height); //左下角圆弧,弧度从1/2PI到PI ctx.arc(radius, height - radius, radius, Math.PI / 2, Math.PI); //矩形左边线 ctx.lineTo(0, radius); //左上角圆弧,弧度从PI到3/2PI ctx.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2); //上边线 ctx.lineTo(width - radius, 0); //右上角圆弧 ctx.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2); //右边线 ctx.lineTo(width, height - radius); ctx.closePath(); } // 分享卡片绘制 export const savePoster = (info, callback) => { const { logoUrl, nickName, price, num, shareBg, avatar } = info; const canvas = uni.createCanvasContext('hoCanvas'); uni.getImageInfo({ src: logoUrl, success: (logoRes) => { canvas.drawImage(shareBg, 0, 0, 300, 240); fillRoundRect(canvas, 10, 37, 160, 160, 10, logoRes.path); canvas.setFontSize(12); canvas.setFillStyle("#333"); // canvas.setStrokeStyle('#333'); canvas.fillText('最高返', 180, 88); canvas.setFontSize(12); canvas.setFillStyle("#FD3540"); canvas.setStrokeStyle('#FD3540'); canvas.fillText('¥', 216, 88); canvas.setFontSize(24); canvas.setFillStyle("#FD3540"); canvas.setStrokeStyle('#FD3540'); canvas.fillText(price, 225, 88); canvas.setFontSize(16); canvas.setFillStyle("#3D3D3D"); canvas.setStrokeStyle('#3D3D3D'); canvas.fillText('霸王餐', 174, 110); canvas.setFontSize(16); canvas.setFillStyle("#FD3540"); canvas.setStrokeStyle('#FD3540'); canvas.fillText(`限量${num}份!`, 222, 110); fillRoundRect(canvas, 4, 210, 22, 22, 11, avatar); canvas.setFontSize(12); canvas.setFillStyle("#FFFFFF"); canvas.setStrokeStyle('#FFFFFF'); canvas.fillText(`${nickName}为您推荐`, 30, 225); canvas.draw(false, () => { // 获取 canvas 的临时路径 uni.canvasToTempFilePath({ canvasId: 'hoCanvas', success: (tempFilePathRes) => { const tempFilePath = tempFilePathRes.tempFilePath; callback(tempFilePath); console.log('临时路径:', tempFilePath); }, fail: (err) => { console.error('获取临时路径失败:', err); } }); }); }, fail: (err) => { console.error('获取分享图片信息失败:', err); message(`获取店铺图片信息失败,请稍后重试`) } }); } // 获取图片path【店铺分享背景、用户头像】 export const getImgPath = (img, name, callback) => { uni.getImageInfo({ src: img, success: (imgRes) => { callback(imgRes.path); }, fail: (err) => { console.error(`获取${name}图片信息失败,请稍后重试`, err); } }) }