我正在尝试创建一个页面,其中屏幕中间有一条黑线,当我在 x 轴上移动鼠标时,该线应该倾斜 - 随着时间的推移,它应该倾斜得更多并且更多,直到最终达到 90 度。
这是我到目前为止的代码,警告 javascript 有一个 while(true) 循环,可能会导致浏览器卡住:https://jsfiddle.net/79ggc2hp/
将代码复制粘贴到此处:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XYZ</title>
<style>
body, html {
height: 100%;
}
</style>
</head>
<body>
<svg height="100%" width="100%">
<line x1="50%" y1="50%" x2="50%" y2="90%" style="stroke:rgb(0,0,0);stroke-width:10" />
</svg>
<script>
var pressureFactor = 10;
var randomizerCorrection = 0;
var randomizer = 0;
var swingfactor = 1;
var time = 0;
var cursorX;
document.onmousemove = function(e){
cursorX = e.clientX;
}
while (true) {
if (randomizerCorrection < randomizer) {
randomizerCorrection = randomizerCorrection + 0.1;
}
if (randomizerCorrection > randomizer) {
randomizerCorrection = randomizerCorrection - 0.1;
}
var Faktor = ((cursorX / 40) - 10) + (this._rotation / pressureFactor);
this._rotation = this._rotation + Faktor + randomizerCorrection * swingfactor;
rotationLine = this._rotation;
if (rotationLine > 90) {
this._rotation = 90;
}
if (rotationLine < (-90)) {
this._rotation = (-90);
}
pressureFactor = pressureFactor - 1;
if (pressureFactor == 1) {
pressureFactor = 1;
swingfactor =+ 1;
}
randomizer = Math.random(5) - 2;
time = time + 1;
}
</script>
</body>
</html>
正如您可能看到的那样,事情无法正常工作,但我有点困惑于在哪里修复问题 - 因为其中一些是通过 Google 和
rotationLine = this._rotation
最终应该旋转线路。
最佳答案
该 while 循环没有中断条件,因此它将无限运行,并且浏览器中不会呈现任何内容。您可能误解了代码和渲染如何交互。当 JavaScript 代码运行完毕后,浏览器就会更新框架并渲染屏幕。但你的代码永远不会停止运行。将其视为需要“浮出水面呼吸空气”。我将省略有关在多线程环境中执行此操作的其他方法的讲座,现在只需指出您需要停止代码,让浏览器呈现,然后再次启动代码。
传统的方法是用简单的 setInterval 替换 while 循环:
setInterval(function() {
if (randomizerCorrection < randomizer) {
randomizerCorrection = randomizerCorrection + 0.1;
}
if (randomizerCorrection > randomizer) {
randomizerCorrection = randomizerCorrection - 0.1;
}
[etc...]
}, 13) // where the second argument is the number of milliseconds between calls.
新的学校方式是使用requestAnimationFrame ,但我现在只是尝试使用 setInterval ,直到您习惯这些概念为止。
关于javascript - 根据鼠标 X 倾斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38204057/