微信公众号前端模版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.0 KiB

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1,maximum-scale=1,minimum-scale=1" >
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<title>Document</title>
</head>
<body>
<div id="btn-image"
style="border:1px solid gray;padding: 10px;">测试</div>
<img src=""
id="img_test"
alt="">
<script>
const btn = document.querySelector('#btn-image')
btn.onclick = () => {
console.log(123);
const input = document.createElement('input')
input.setAttribute('type', 'file')
input.setAttribute('accept', '*')
input.onchange = (e) => {
const file = e.target.files[0]
const render = new FileReader() // 创建读取文件对象
render.readAsDataURL(file) // 读取file文件,得到的结果为base64
render.onload = function () {
// result
const renderImg = new Image()
renderImg.src = render.result // 把读取到的base64图片设置给img的src属性
renderImg.onload = function () {
const imgWidth = renderImg.width
const imgHeight = renderImg.height
const canvas = document.createElement('canvas') // 如果不需要放在页面上,使用js创建该元素就可以了
const canvasContent = canvas.getContext('2d')
canvas.width = imgWidth
canvas.height = imgHeight
canvasContent.drawImage(renderImg, 0, 0, imgWidth, imgHeight) // 绘画到画布上
const base64 = canvas.toDataURL(file.type, 1)
console.log(base64);
const domImg = document.querySelector('#img_test')
domImg.src = base64
}
}
}
input.click()
}
</script>
</body>
</html>