JavaScript效果——跟随图片变化改变网页背景,效果如下所示:
基础模板
首先我们准备基础模板,模板代码如下所示:
<script setup>
import { ref } from 'vue'
const images = ref([
'https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF',
'https://t7.baidu.com/it/u=825057118,3516313570&fm=193&f=GIF',
'https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF',
'https://t7.baidu.com/it/u=1285847167,3193778276&fm=193&f=GIF'
])
const width = '200px'
const hoverIndex = ref(-1)
async function handleMouseEnter(img, i) {
hoverIndex.value = i
}
function handleMouseLeave() {
hoverIndex.value = -1
}
</script>
<template>
<img
v-for="(url, i) in images"
crossorigin="anonymous"
:src="url"
:style="{
width: width,
opacity: hoverIndex === -1 ? 1 : i === hoverIndex ? 1 : 0.2
}"
@mouseenter="handleMouseEnter($event.target, i)"
@mouseleave="handleMouseLeave"
/>
</template>
基础模板效果如下:
引入ColorThief库
要想实现跟随图片变化实现网页背景渐变效果,我们需要获取图片主要的三种颜色,这里我们使用ColorThief库中的getPalette方法,该方法语法格式如下:
const colorThief = new ColorThief() // 创建ColorThief的实例对象
const colors = colorThief.getPalette(image,colorCount)
其中:
-
image:要提取颜色的图像对象或 URL; -
colorCount:提取的颜色数量。默认值为 10;
该方法返回颜色谱。
获取图片主要颜色
简单了解了colorThief.getPalette方法后,接下来我们修改鼠标移入方法通过getPalette方法获取图片主要的三种颜色,示例代码如下:
import ColorThief from 'colorthief' // 引入ColorThief库
const colorThief = new ColorThief() // 创建ColorThief的实例对象
async function handleMouseEnter(img, i) {
hoverIndex.value = i
const colors = colorThief.getPalette(img, 3) // 获取颜色谱
const [c1, c2, c3] = colors.map((c) => `rgb(${c[0]},${c[1]},${c[2]})`) // 解构出三组rgb
console.log(c1, c2, c3)
}
当我们鼠标移入图片时,就会打印出图片的主要三种颜色。
实现渐变效果
获取图片的主要颜色后,接下来设置网页的渐变背景,CSS代码如下:
<style>
html {
background-image: linear-gradient(to bottom, var(--c1), var(--c2), var(--c3)); // 背景图像
background-repeat: no-repeat; // 不重复
height: 100%;
}
</style>
设置网页渐变背景后,接下来在鼠标移入事件中添加如下代码:
html.style.setProperty('--c1', c1)
html.style.setProperty('--c2', c2)
html.style.setProperty('--c3', c3)
这样就这样就实现了鼠标移入时,背景发生改变,接下来修改鼠标移除事件,代码如下:
function handleMouseLeave() {
hoverIndex.value = -1
html.style.setProperty('--c1', '#fff')
html.style.setProperty('--c2', '#fff')
html.style.setProperty('--c3', '#fff')
}
好了,这样就实现了跟随图片变化改变网页背景了。
原文始发于微信公众号(白巧克力LIN):JavaScript——跟随图片变化改变网页背景色
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/222449.html