SOURCE

console 命令行工具 X clear

                    
>
console
function compressAndToBase64 (file, dimRate = 0.75, quality = 0.8) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = e => {
      const img = new Image()
      img.src = e.target.result
      img.onload = () => {
        var canvas = document.createElement('canvas')
        canvas.width = img.naturalWidth * dimRate
        canvas.height = img.naturalHeight * dimRate
        canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height)
        resolve(canvas.toDataURL(file.type, quality))
      }
      img.onerror = reject
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/**
 * 拍照或从相册选择图片
 * @param {boolean} cameraOnly 是否只来自相机
 */
function getPicture (cameraOnly = false) {
  return new Promise((resolve, reject) => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    if (cameraOnly) {
      input.capture = 'camera'
    }
    input.style = `position: absolute;opacity: 0;transform: scale(0);`
    document.body.append(input)
    input.addEventListener('change', e => {
      Promise.all(Object.values(e.target.files).map(ele => compressAndToBase64(ele)))
        .then(resolve, reject)
        .finally(() => input.remove())
    })
    input.click()
  })
}


document.querySelector('#camera').onclick = () => getPicture(true).then(console.log)
document.querySelector('#cameraAlbum').onclick = () => getPicture().then(console.log)
<h1>customized upload</h1>
<a href="javascript:;" class="file">选择文件
	<input type="file" name="" id="">
</a>

<hr>

<h1>choose image</h1>
<button id="camera">拍照</button>
<button id="cameraAlbum">拍照 & 相册</button>
.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}

本项目引用的自定义外部资源