我試圖使用transform rotate將紅色div指向視窗的角落。
黃色是固定的45度,僅作參考。
藍色指向左上角。
藍色以innerHeight和innerWidth為點,指向左上角。
而紅色試圖通過計算45度 一些偏移量來模仿藍色,它必須始終擁有與藍色相同的旋轉,但沒有使用innerHeight和innerWidth作為點。
這是我最接近于使其作業的代碼:
。window。 onresize = () =>/span> calcAngle()
var calcAngle = (/span>) => {
console.clear()
var x1 = 0, y1 = 0。
var x2 = window.innerWidth,y2 = window.innerHeight。
var a = (Math.atan2((y2 - x1), (x2 - y1) * (180 / Math.PI))。)
document.querySelectorAll(".pointer")[1] 。 style.transform = "translate(50%, -50%) rotate("/span> a "deg)"
var of = x2/y2。
var ang = 45;
var calc = ang - (ang*of-ang)
document.querySelectorAll(".pointer") [2]。 style.transform = "translate(50%, -50%) rotate(" (calc) "deg)"
console.log(a, calc)
}
calcAngle();
body {
overflow: hidden;
}
.pointer {
width: 200px;
height: 20px;
opacity: .7;
background: 藍色。
position: absolute;
top: 50%;
right: 50%;
transform: translate(50%, -50%)。
clip-path: polygon(100% 0%, 100% 100%, 0% 50%)。)
}
.pointer:nth-child(1){
background: 黃色。
transform: translate(50%, -50%) rotate(45deg)。
}
.pointer:nth-child(3){
background: red;
}
< div class="pointer"></div>
<div class="pointer"/span>> </div>>
<div class="pointer"/span>> </div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
以代碼為例,calc必須始終具有相同的a值,但使用45度作為參考。
uj5u.com熱心網友回復:
當然,正如你在問題中所示,最簡單的方法是使用atan(y/x) * 180 / PI來獲得整個角度。這在下面反映為refAngle。
由于你的條件要求是45度的偏移,這需要更高級的數學,除了基本的三角函式之外,還要使用正弦律。根據螢屏的寬/高比例,我們有足夠的資訊可以找到,但最終是一個非常復雜的公式。這反映在下面的兩個步驟中,首先是sinOff,以獲得相對于45度的偏移角的正弦,然后是off,一旦我們完成了asin和從弧度到度的轉換。
這個片段展示了兩個角度的一致性,無論瀏覽器視窗如何調整大小。
。const x = window.innerWidth;
const y = window.innerHeight。
const { sin, atan, asin, sqrt, PI } = Math;
const sinOff = sin(atan(y/x)) / (sqrt(2)*y) * (x-y) 。
const off = asin(sinOff) * 180 / PI。
const angle = 45 - off;
const refAngle = atan(y/x) * 180 / PI。
console.log(angle, refAngle);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
注意,由于公式非常復雜,我使用結構化來減少Math.的混亂。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/331091.html
標籤:
