あなたはこれを行うにはいくつかのより多くの計算を行う必要があります。
中間を見つけるには、ビューポートの幅と高さを知る必要があります。次に、マウスの位置を正規化して、e.xが行っていたときの左上からではなく中心線からのオフセットを計算する必要があります。
"modifier"でオフセットの暴力を変更できるようにする必要があります。
<html>
<head>
</head>
<body>
<img id="logo" src="http://placehold.it/150x150" style="position:absolute;" />
<script>
window.onload = setInitialLogoPosition;
document.onmousemove = updateLogoPosition;
function setInitialLogoPosition(){
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
logo.style.left = leftOffset;
logo.style.top = topOffset;
}
function updateLogoPosition(e){
// Get height and width of body
var bodyHeight = document.body.clientHeight;
var bodyWidth = document.body.clientWidth;
// Get height and width of logo
var logo = document.getElementById("logo");
var logoWidth = logo.width;
var logoHeight = logo.height;
/* Normalise the mouse so that 0 is the centre
with negative values to the left and positive to the right */
var x = (e.x/bodyWidth * 100) - 50;
var y = (e.y/bodyHeight * 100) - 50;
// Calculate the position of the logo without mouse manipulation
var leftOffset = (bodyWidth/2 - logoWidth/2);
var topOffset = (bodyHeight/2 - logoHeight/2);
// Set violence of offset
var modifier = 0.5;
// Add the mouse offset to the central position
leftOffset += (x * modifier);
topOffset += (y * modifier);
// Apply the calculated position to the logo
logo.style.left = leftOffset + "px";
logo.style.top = topOffset + "px";
}
</script>
</body>
</html>
ここで画像はどこにあるはずですか? – Thinker
私はそれが中心に見えるようにします。マウスが動くとき、それはマウスと同じx量を動かすが、中央に留まる。 – MonkeyAtWork
イメージを縦にセンタリングしますか? – Alexis