然后就可以在 onPaste 变乱内里直接行使了:
- document.querySelector('.editor').addEventListener('paste', async (e) => {
- const result = await onPaste(e)
- console.log(result)
- })
上面的代码支持文本名目,接下来就要对图片名目举办处理赏罚了。玩过 <input type="file"> 的同窗会知道,包罗图片在内的全部文件名目内容城市储存在 File 工具内里,这在剪贴板内里也是一样的。于是我们可以编写一套通用的函数,专门来读取 File 工具里的图片内容,并把它转化成 base64 字符串。
粘贴图片
为了更好地在输入框里展示图片,必需限定图片的巨细,以是这个图片处理赏罚函数不只可以或许读取 File 工具内里的图片,还可以或许对其举办压缩。
新建一个 chooseImg.js 文件:
- /**
- * 预览函数
- *
- * @param {*} dataUrl base64字符串
- * @param {*} cb 回调函数
- */
- function toPreviewer (dataUrl, cb) {
- cb && cb(dataUrl)
- }
- /**
- * 图片压缩函数
- *
- * @param {*} img 图片工具
- * @param {*} fileType 图片范例
- * @param {*} maxWidth 图片最大宽度
- * @returns base64字符串
- */
- function compress (img, fileType, maxWidth) {
- let canvas = document.createElement('canvas')
- let ctx = canvas.getContext('2d')
- const proportion = img.width / img.height
- const width = maxWidth
- const height = maxWidth / proportion
- canvas.width = width
- canvas.height = height
- ctx.fillStyle = '#fff'
- ctx.fillRect(0, 0, canvas.width, canvas.height)
- ctx.drawImage(img, 0, 0, width, height)
- const base64data = canvas.toDataURL(fileType, 0.75)
- canvas = ctx = null
- return base64data
- }
- /**
- * 选择图片函数
- *
- * @param {*} e input.onchange变乱工具
- * @param {*} cb 回调函数
- * @param {number} [maxsize=200 * 1024] 图片最概略积
- */
- function chooseImg (e, cb, maxsize = 200 * 1024) {
- const file = e.target.files[0]
- if (!file || !//(?:jpeg|jpg|png)/i.test(file.type)) {
- return
- }
- const reader = new FileReader()
- reader.onload = function () {
- const result = this.result
- let img = new Image()
- if (result.length <= maxsize) {
- toPreviewer(result, cb)
- return
- }
- img.onload = function () {
- const compresscompressedDataUrl = compress(img, file.type, maxsize / 1024)
- toPreviewer(compressedDataUrl, cb)
- img = null
- }
- img.src = result
- }
- reader.readAsDataURL(file)
- }
- export default chooseImg
关于行使 canvas 压缩图片和行使 FileReader 读取文件的内容在这里就不赘述了,感乐趣的读者可以自行查阅。 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|