问题
I am using a function from mourner/suncalc that allows me to get the current position of our sun. With getPosition()
, I want to create an animation on a image or with pure CSS (scaleable to different screen resolutions and orientations, of course), where you can see where the sun is right now in real time on the page. A totally unnecessary function but a fun function :) The image below illustrates how I am thinking.
Like I said, I'll be using the getPosition()
function from mourner's function which prints azimuth and altitude of the sun. The problem I am facing now, is to somehow convert this data to percents or pixels, so the sun in my example image above moves along the round line (and yes, the sun must be blocked by the straight line that imitates the ground), imitating the real position on the sky in real life.
The azimuth data looks like -0.7000179547193575 and the altitude like this: -0.699671080144066 (based on the current sun position where I am right now).
How do I accomplish this? Can I do this with pure CSS or do I have to do it with images?
回答1:
I don't know the exact formula but here is an idea how you can create this using CSS then you simply have to adjust different values.
var sun = document.querySelector('.sun');
function update() {
var x = Math.random() * 180;
var y = Math.random() * 40;
sun.style.transform="rotateX("+y+"deg) rotate("+x+"deg)"
}
.container {
width:300px;
height:150px;
margin:auto;
overflow:hidden;
border:1px solid;
}
.sun {
margin:20px;
padding-top:calc(100% - 40px);
position:relative;
border-radius:50%;
border:1px solid grey;
transform:rotateX(20deg) rotate(20deg);
background:
linear-gradient(red,red) center/100% 1px;
background-repeat:no-repeat;
transition:1s;
}
.sun:before {
content:"";
position:absolute;
top:calc(50% - 20px);
left:-20px;
width:40px;
height:40px;
background:yellow;
border-radius:50%;
}
<div class="container">
<div class="sun">
</div>
</div>
<button onclick="update()">update</button>
Using the code below you simply need to convert your values to a degrees in order to rotate the sun
element and place the sun in the correct place.
回答2:
You can change css values by using JavaScript, I do not see any other way
/* yes this JS code */
const
MvSun = document.getElementById('Mv-Sun'),
Sun = document.getElementById('sun')
;
MvSun.onclick = function() {
Sun.style.left = '200px';
}
#celestial-vault {
position: relative;
width: 400px;
height: 300px;
background-color: skyblue;
display: block;
}
#sun {
position: absolute;
top: 10px;
left: 20px;
background-color:yellow;
width:20px;
height:20px;
border-radius: 10px;
display: block;
}
<div id="celestial-vault">
<div id="sun"></div>
</div>
<button id="Mv-Sun">move sun</button>
来源:https://stackoverflow.com/questions/54836891/show-where-the-sun-is-on-the-sky-in-real-time-how