如何用純 CSS 繪制一個世界上不存在的彭羅斯三角形
阿新 • • 發佈:2018-11-21
htm pla posit 一個 ati 地址 tle 演示 open
本地下載
效果預覽
在線演示
按下右側的“點擊預覽”按鈕可以在當前頁面預覽,點擊鏈接可以全屏預覽。
https://codepen.io/comehope/pen/RyvgMZ
可交互視頻教程
此視頻是可以交互的,你可以隨時暫停視頻,編輯視頻中的代碼。
請用 chrome, safari, edge 打開觀看。
https://scrimba.com/c/czPkasr
源代碼下載
本地下載
每日前端實戰系列的全部源代碼請從 github 下載:
https://github.com/comehope/front-end-daily-challenges
代碼解讀
定義 dom,一個容器中包含 3 個 <span>:
<div class="penrose">
<span></span>
<span></span>
<span></span>
</div>
居中顯示:
html, body { height: 100%; display: flex; align-items: center; justify-content: center; background-color: black; }
定義容器尺寸:
.penrose {
width: 20em;
height: 20em;
}
畫出包含 3 條邊的容器:
.penrose { position: relative; } .penrose span { position: absolute; width: 100%; height: 100%; } .penrose span:nth-child(1) { transform: rotate(0deg); } .penrose span:nth-child(2) { transform: rotate(120deg); } .penrose span:nth-child(3) { transform: rotate(240deg); }
為 3 條邊所屬的容器上色:
.penrose {
color: red;
}
.penrose span {
background-color: currentColor;
}
.penrose span:nth-child(1) {
filter: brightness(1);
}
.penrose span:nth-child(2) {
filter: brightness(0.66);
}
.penrose span:nth-child(3) {
filter: brightness(0.33);
}
用遮罩切出每一條邊,組成彭羅斯三角形:
.penrose span {
clip-path: polygon(57% 0, 75% 0, 26% 85%, 89.5% 85%, 98.4% 100%, 0 100%);
}
.penrose span:nth-child(2) {
top: 18.3%;
left: 43.3%;
}
.penrose span:nth-child(3) {
top: 46.5%;
left: 5.9%;
}
定義旋轉動畫效果:
.penrose {
animation: rotating 30s linear infinite;
transform-origin: 66% 66%;
}
@keyframes rotating {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
最後,增加旋轉時變色的效果:
@keyframes rotating {
0% {
color: red;
transform: rotate(0deg);
}
20% {
color: yellow;
}
40% {
color: lime;
}
60% {
color: blue;
}
80% {
color: fuchsia;
}
100% {
color: red;
transform: rotate(720deg);
}
}
大功告成!
原文地址:https://segmentfault.com/a/1190000014946883
如何用純 CSS 繪制一個世界上不存在的彭羅斯三角形