2017-07-28 71 views
-2

我希望縮放比例隨着鼠標靠近物體而增加,當鼠標懸停在中心時,最大縮放比例應該是。我怎樣才能使用Javascript來做到這一點?基於相對鼠標懸停距離更改比例?

function myFunction() { 
 
    document.getElementsByTagName("circle")[0].setAttribute("r", "100"); 
 
}
svg { 
 
    border-style: solid; 
 
    border-color: black; 
 
    background-color: white; 
 
}
<svg> 
 
<circle cx="145" cy="80" r="40" fill="red" onmouseover="myFunction()"/> 
 
</svg> 
 

 
<p> 
 
    Move mouse closer to circle to increase size 
 
</p>

https://jsfiddle.net/tahirjuba/2r5ufd8z/7/

+0

難道你們不知道我的意思嗎? – tjuba

+0

使用'mousemove'事件,從事件對象獲取鼠標座標,計算距離,並適當設置圓的半徑(或'transform =「scale(X)」')。 –

+0

但是直到你自己發佈一個合法的嘗試,我們都不會有太大的幫助。 –

回答

0

你的意思是這樣?

var circle = document.getElementById("circle"); 
 

 
function myFunction(evt) { 
 
    var r = Math.abs(evt.x - parseInt(evt.target.getAttribute('cx'), 10)) + Math.abs(evt.y - parseInt(evt.target.getAttribute('cy'), 10)); 
 
    r += 10; 
 
    document.getElementsByTagName("circle")[0].setAttribute("r", r); 
 
}
svg { 
 
    border-style: solid; 
 
    border-color: black; 
 
    background-color: white; 
 
}
<svg> 
 
<circle id="circle" cx="145" cy="80" r="40" fill="red" onmousemove="myFunction(evt)"/> 
 
</svg> 
 

 
<p> 
 
    Move mouse closer to circle to increase size 
 
</p>

+0

你是否得到了鼠標的座標,並以某種方式將它們應用於'r'? – tjuba

+0

@tjuba是的,它有什麼'r'的功能。它採用mousevent x和svg座標x之間的差異,並將其添加到mousevent y和svg座標y之間的差異。然後我使用結果'r'作爲圓的半徑(+ 10像素,所以圓永遠不會完全消失)。 –

+0

謝謝,那麼如果我想改變鼠標移動的不同屬性,比如不透明度怎麼辦。我可以替換什麼東西? – tjuba