Kazaf's blog Kazaf's blog
首页
  • javascript
  • typescript
  • vue
  • react
  • babel
  • nginx
GitHub (opens new window)

Kazaf

前端打字员
首页
  • javascript
  • typescript
  • vue
  • react
  • babel
  • nginx
GitHub (opens new window)
  • JavaScript

    • js-发布订阅模式实现EventBus
    • js-手写数组常用方法的实现
    • 手写JS代码收集
    • 工具方法收集
      • 获取文本宽度
      • canvas 压缩图片分辨率
      • vue 延迟加载图片指令
      • file或blob转base64
      • base64转file或blob
      • 图片URL转base64
  • Typescript

  • Vue

  • react

  • 前端
  • JavaScript
Kazaf
2022-05-20

工具方法收集

# 工具方法收集

# 获取文本宽度

export const getTextWidth = (text, options = {}) => {
  const {
    size = 14,
    family = 'Microsoft YaHei'
  } = options
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  ctx.font = `${size}px ${family}`
  const metrics = ctx.measureText(text)
  return Math.abs(metrics.actualBoundingBoxLeft) + Math.abs(metrics.actualBoundingBoxRight)
}
1
2
3
4
5
6
7
8
9
10
11

# canvas 压缩图片分辨率

export const compressionImage = imgSrc => {
  const image = new Image()
  
  image.setAttribute('crossOrigin', 'Anonymous')
  image.src = imgSrc

  return new Promise(resolve => {
    image.onload = function () {
      // 图片原始宽高
      const imgWidth = image.width
      const imgHeight = image.height

      // 创建画布
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')

      // 图像压缩比例
      const ratio = 0.7

      // 压缩后宽高
      const compressionWidth = imgWidth * ratio
      const compressionHeight = imgHeight * ratio

      // 画布宽高
      canvas.width = compressionWidth
      canvas.height = compressionHeight

      // 裁剪图片
      context.drawImage(image, 0, 0, imgWidth, imgHeight, 0, 0, compressionWidth, compressionHeight)

      resolve(canvas.toDataURL('image/jpg'))
    }
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# vue 延迟加载图片指令

export const directives = {
  install(app) {
    /* v-lazy指令 */
    app.directive('lazy', {
      mounted(imgEl, binding) {
        const src = binding.value

        if (!src) return

        const intersectionObserver = new IntersectionObserver(
          function (entries) {
            entries.forEach((item) => {
              /* intersectionRatio > 0 图片出现 */
              if (item.intersectionRatio > 0) {
                item.target.src = src
                intersectionObserver.unobserve(item.target)
              }
            })
          },
          { threshold: [0] }
        )
        
        intersectionObserver.observe(imgEl)
      }
    })
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# file或blob转base64

/**
 * file或blob转base64
 * @param {*} blob file或者blob
 * @param {*} callback function (data) 通过参数获得base64
 */
function blobToBase64(blob, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', ()=> {
    callback(reader.result)
  })
  reader.readAsDataURL(blob)
}
1
2
3
4
5
6
7
8
9
10
11
12

# base64转file或blob

/**
 * base64转file
 * base64格式:data:image/pngbase64,iVBORw0KGgoAAAANSU...
 * @param {*} dataURL base64编码数据
 * @param {*} filename 文件名称
 */
function dataURLToFile(dataURL, filename) {
  const arr = dataURL.split(',')
  const mime = arr[0].match(/:(.*?)/)[1] // mime类型 image/png
  const bstr = atob(arr[1]) //base64 解码

  let i = bstr.length

  const u8arr = new Uint8Array(i)

  while (i--) {
    u8arr[i] = bstr.charCodeAt(i)
  }

  return new File([u8arr], filename, { type: mime })
  //return new Blob([a8arr], {type: mime})
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 图片URL转base64

/**
 * 图片地址转base64
 * base64格式:data:image/pngbase64,iVBORw0KGgoAAAANSU...
 * @param {*} url 图片地址
 * @param {*} callback 回调函数
 */
function imgUrlToBase64(url, callback) {
  let img = new Image()
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')

  img.crossOrigin = 'anonymous'
  img.onload = function () {
    canvas.width = img.width
    canvas.height = img.height

    ctx.drawImage(img, 0, 0)
    callback(canvas.toDataURL())
  }
  img.src = url
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
编辑 (opens new window)
#JavaScript
上次更新: 2022/07/05, 17:24:58
手写JS代码收集
Ts高级类型-UtilityTypes

← 手写JS代码收集 Ts高级类型-UtilityTypes→

最近更新
01
React中的受控和非受控组件
09-22
02
nginx基本配置
06-01
03
vue添加水印
05-26
更多文章>
Theme by Vdoing | Copyright © 2021-2022
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式