Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

html - Keep box-shadow direction consistent while rotating

When giving e.g. a <div> a box-shadow as well as rotating it will cause a rotation of the box-shadow direction - which is problematic when the box-shadow should create an illusion of lighting.

Example: https://jsfiddle.net/5h7z4swk/

div {
  width: 50px;
  height: 50px;
  margin: 20px;
  box-shadow: 10px 10px 10px #000;
  display: inline-block;
}
#box1 {
  background-color: #b00;
}
#box2 {
  background-color: #0b0;
  transform: rotate(30deg);
}
#box3 {
  background-color: #00b;
  transform: rotate(60deg);
}
#box4 {
  background-color: #b0b;
  transform: rotate(90deg);
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
#box6 {
  background-color: #0bb;
  animation-name: spin;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box6"></div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Keeping direction of an offset box-shadow consistent during rotation is simple with CSS transforms.
This approach relies on the fact that the transform origin is moved with the transforms. This means that when several transforms are set on the same element, the coordinate system of each transform changes according to the previous ones.

In the following example, the blue element is a pseudo element and the shadow is the div element:

div {
  width: 40px; height: 40px;
  margin: 40px;
  box-shadow: 0px 0px 10px 5px #000;
  animation: spinShadow 2s infinite;
  background-color: #000;
}
@keyframes spinShadow {
  to { transform: rotate(360deg); }
}
div:before {
  content: '';
  position: absolute;
  left:-5px; top:-5px;
  width: 50px; height: 50px;
  transform: rotate(0deg) translate(-10px, -10px) rotate(0deg);
  animation:inherit;
  animation-name: spinElt;
  background-color: #0bb;
}
@keyframes spinElt {
  to { transform: rotate(-360deg) translate(-10px, -10px) rotate(360deg); }
}
<div></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...