Bläddra i källkod

分享海报头像绘制调整

Xiao_123 4 månader sedan
förälder
incheckning
df995d78fc
1 ändrade filer med 13 tillägg och 4 borttagningar
  1. 13 4
      pagesB/sharePoster/index.vue

+ 13 - 4
pagesB/sharePoster/index.vue

@@ -55,14 +55,23 @@ const getImageTempRatio = (url) => {
 }
 
 // 个人头像
-const drawAvatar = (ctx, imagePath, x, y, radius) => {
+const drawAvatar = (ctx, imagePath, x, y, radius, w, h) => {
   ctx.save() // 保存当前绘图上下文
   // 绘制圆形裁剪路径
   ctx.beginPath();
   ctx.arc(x + radius, y + radius, radius, 0, 2 * Math.PI)
   ctx.clip();
+  const rate = w / h
   // 绘制图片
-  ctx.drawImage(imagePath, x, y, 2 * radius, 2 * radius) // 注意这里的宽高是直径的2倍
+  if (rate > 1) {
+    const _len = 2 * radius / rate // lenH
+    const _yStart = radius - _len / 2 + y
+    ctx.drawImage(imagePath, x, _yStart, 2 * radius, _len) // 注意这里的宽高是直径的2倍
+  } else {
+    const _len = 2 * radius * rate // lenW
+    const _xStart = radius - _len / 2 + x
+    ctx.drawImage(imagePath, _xStart, y, _len, 2 * radius) // 注意这里的宽高是直径的2倍
+  }
   ctx.restore() // 恢复之前保存的绘图上下文
 }
 
@@ -121,8 +130,8 @@ const createPoster = async () => {
   
   // 头像
   const avatarUrl = getUserAvatar(baseInfo.value?.avatar, baseInfo.value?.sex)
-  const { path } = await getImageTempRatio(avatarUrl)
-  drawAvatar(context, path, 124, 22, 40.5) // canvas、图片路径、x、y、半径
+  const { path, width, height } = await getImageTempRatio(avatarUrl)
+  drawAvatar(context, path, 124, 22, 40.5, width, height) // canvas、图片路径、x、y、半径
 
   //分享二维码
   // const { path: qrCode } = await getImageTempRatio('https://minio.citupro.com/dev/menduner/miniProgram.jpg')