<input id="file" type="file" accept="image/*" />
<button id="button">生成HTML</button>
const btn = document.getElementById('button')
const fileDom = document.getElementById('file')
// 根据选择的文件生成图片对象
function loadImage() {
const file = fileDom.files[0]
if (!file) return null
const objUrl = URL.createObjectURL(file)
const img = new Image()
return new Promise(resolve => {
img.onload = () => {
resolve(img)
}
img.onerror = () => {
resolve(null)
}
img.src = objUrl
})
}
// 创建div的html
function createHTML(width, height, bmp) {
// 阴影css片段
const shadowCSSFragments = []
// 鼠标移入css阴影片段
const shadowCSSHover = []
// 读取每个位图像素点
for (let r = 0; r < height; r++) {
for (let c = 0; c < width; c++) {
const i = r * width + c
const R = bmp[i * 4]
const G = bmp[i * 4 + 1]
const B = bmp[i * 4 + 2]
const A = bmp[i * 4 + 3] / 255
shadowCSSFragments.push(`${c + 1}px ${r}px rgba(${R}, ${G}, ${B}, ${A})`)
// shadowCSSHover.push(`${c + 1}px ${r}px rgba(${255 - R}, ${255 - G}, ${255 - B}, ${A})`)
}
}
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>css实现图片</title>
<style>
.shadow-img {
width: ${width}px;
height: ${height}px;
}
.shadow-img .inner {
width: 1px;
height: 1px;
box-shadow: ${shadowCSSFragments.join(',')};
transition: 0.5s;
}
<--!注释调hover效果 .shadow-img:hover .inner {
box-shadow: ${shadowCSSHover.join(',')};
}-->
</style>
</head>
<body>
<div class="shadow-img">
<div class="inner"></div>
</div>
</body>
</html>
`
}
// 下载生成好的html
function download(html) {
const blob = new Blob([html], {
type: 'text/html'
})
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.style.display = 'none'
a.download = 'demo.html'
a.click()
}
async function generate() {
// 得到图片对象
const img = await loadImage()
// 没有直接返回
if (!img) return
// 图片绘制到canvas上
const cvs = document.createElement('canvas')
cvs.width = img.width
cvs.height = img.height
const ctx = cvs.getContext('2d')
ctx.drawImage(img, 0, 0)
// 获取canvas中的位图
const bmp = ctx.getImageData(0, 0, img.width, img.height).data
const html = createHTML(img.width, img.height, bmp)
// 下载html
download(html)
}
btn.onclick = generate
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.