笔记:前端水印addWatermark

56 阅读1分钟

场景:有时需要前端在上传之前修改文件,给图片添加水印.

思路:就是在文件上传之前改变文件,给图片添加水印即可.

👇相关代码👇

async addWatermark(file) {
      const fileTypeList = ['png','jpg']
      const filesType = file.name.split(".")[1];
      // 判断是否是图片
      if (fileTypeList.includes(filesType)) {
        return file;
      } else {
        return new Promise((resolve, reject) => {
          // 创建文件流
          const reader = new FileReader();
          // 读取文件结束回调
          reader.onload = (event) => {
            const img = new Image();
            img.onload = () => {
              const canvas = document.createElement("canvas");
              const context = canvas.getContext("2d");
              canvas.width = img.width;
              canvas.height = img.height;
              context.drawImage(img, 0, 0);
              const fontSize = img.width / 2 / 14;
              context.font = `${fontSize}px Arial`;
              context.fillStyle = "rgb(231,231,231)";
              // 获取偏移量 方便后面文字水印排版
              let offset = parseInt(context.font);
              context.translate(-img.width / 20, -img.height / 2.5);
              context.fillText(
                `第一行内容`,
                img.width / 2 - fontSize * 12,
                img.height / 2
              );
              context.translate(0, offset);
              context.fillText(
                `第二行内容ID:${this.collectors.orgId}`, // 这里可以任何变量
                img.width / 2 - fontSize * 12,
                img.height / 2
              );
              context.translate(0, offset);
              context.fillText(
                `第三行内容:${this.collectors.channelName}`,
                img.width / 2 - fontSize * 12,
                img.height / 2
              );
              // 把最新的canvas转换成base64地址url 
              const base64 = canvas.toDataURL();
              const blob = this.dataURLtoBlob(base64);
              const resultFile = new File([blob], file.name, {
                type: "image/jpeg",
              });
              // 抛出改造好的图片文件
              resolve(resultFile);
            };
            img.src = event.target.result;
          };
          reader.readAsDataURL(file);
        });
      }
    },
`