Skip to content

CSS 碰撞变色小球

Published: at 02:49 AMSuggest Changes

需求

每日一题里面的问题

css 实现碰撞变色的小球

实现

答案来自 大佐 巨佬

Codepen: https://codepen.io/wheatup/pen/poQMdKP/365119e821503f753fb778db16b54896

<figure style="--seedX: 1.34; --seedY: 2.41;"></figure>
<figure style="--seedX: 2.41; --seedY: 1.67;"></figure>
@property --x {
	syntax: "<number>";
	inherits: true;
	initial-value: 0;
}

@property --y {
	syntax: "<number>";
	inherits: true;
	initial-value: 0;
}

figure {
	--size: 6rem;
	--time1: calc(var(--seedX) * 1s);
	--time2: calc(var(--seedY) * 1s);
	--phase1: 0;
	--phase2: 0;
	width: var(--size);
	height: var(--size);
	border-radius: var(--size);
	position: absolute;
	top: 0;
	left: 0;
	background-color: hsl(calc((var(--phase1) * 1.43 + var(--phase2) * 2.56) * 30deg), 50%, 50%);
	animation: xpos var(--time1) linear alternate infinite, 
		ypos var(--time2) linear alternate infinite,
		phase1 calc(var(--time1) * 2) steps(4, end) both infinite,
		phase2 calc(var(--time2) * 2) steps(4, end) both infinite;
	transform: translate(calc(var(--x) * (100vw - var(--size))), calc(var(--y) * (100vh - var(--size))));
}

@keyframes xpos {
	to {
		--x: 1;
	}
}

@keyframes ypos {
	to {
		--y: 1;
	}
}

@keyframes phase1 {
	to {
		--phase1: 3.14159;
	}
}

@keyframes phase2 {
	to {
		--phase2: 3.14159;
	}
}

Previous Post
Git 获取代码行数
Next Post
JS Symbol.toPrimitive 详解