原文链接: 使用canvas做纯色或渐变色图片优化 img图片拉伸
上一篇: 纯js 使用canvas制作数字滚动效果
下一篇: cocos 数字滚动
基本思想是对于简单的纯色或者渐变色, 可以使用canvas画出来, 然后导出url, 再在img中缩放拉伸
下面窄的是canvas画的, 理论上只需要画一个像素宽就行了, 下面是img标签渲染的, 拉伸后也不会有模糊, 这种方式可能节省不少流量, 而且加载速度也会快一些, 主要是在一些大型活动中使用, 不过坏处就是必须图像不能太复杂, 不然不太好画
img标签的大小, 最后在外面包一层div, 通过控制外层div的大小来控制img的大小, 而且div可以通过padding实现指定比例的效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#img {
width: 100%;
height: 100%;
}
#div {
width: 200px;
height: 300px;
/* background-size: 100% 100%; */
}
.img-wrap {
width: 200px;
height: 300px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div class="img-wrap">
<img id="img" alt="" />
</div>
<div s id="div" alt="" />
<script>
const clamp = (n, min, max) => {
if (n < min) return min
if (n > max) return max
return n
}
const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")
const img = document.getElementById("img")
const div = document.getElementById("div")
console.log("==", canvas, img)
const w = 10
const h = 255
canvas.width = w
canvas.height = h
const buf = new Uint8ClampedArray(w * h * 4)
for (let i = 0; i < w; i++) {
for (let j = 0; j < h; j++) {
const a = clamp(255 - j, 20, 250)
const r = 0
const g = j > 200 ? 255 : 0
const b = 255
// const r = clamp(j, 30, 220)
// const g = clamp(125 - j, 30, 220)
// const b = clamp(255 - j, 30, 220)
const idx = (j * w + i) * 4
console.log("idx", i, j, idx)
buf[idx] = r
buf[idx + 1] = g
buf[idx + 2] = b
buf[idx + 3] = a
}
}
const imageData = new ImageData(buf, w, h)
console.log(imageData)
ctx.putImageData(imageData, 0, 0)
const url = canvas.toDataURL()
console.log("url", url)
img.src = url
// div.style.backgroundImage = `url(${url}) no-repeat`
// div.style.background = `url(${url})`
// div.style.backgroundSize = "contain"
// div.style.backgroundSize = "cover"
div.style.backgroundImage = `url(${url})`
div.style.backgroundSize = "cover"
// div.style.backgroundSize = "100px 100px"
</script>
</body>
</html>