2016-07-29 135 views
1

我是用JavaScript /帆布玩弄色彩,我想我的對象的顏色取決於從當前鼠標position.This其中心的距離是我當前的功能得到彩色每mousemove事件:獲得從距離

function getColorFromDistance(node1,node2){ 
    var dist = getDist(node1,node2); //Getting distance; 
    var cl = (Math.round(255/dist*255)).toString(16); //this needs to be a propper formula 
    return "#" + cl + cl + cl; //converting to hex 
} 

目前,當距離變爲255時,我會看到一個眨眼效果。 我需要一種方法來使顏色強度取決於距離,這樣鼠標遠離物體越深,鼠標在物體居中它的全白色。你明白了。我只需要公式

+0

基於所述最大值(帆布/窗口的寬度)的百分比。如果您希望的着色版本你可以檢查我的codePen http://codepen.io/kmlzjc/pen/oLrkNb,它不完美,需要一些調整,但我認爲這主要是你想要的。它使用css hls使事情更容易計算。 –

+0

太棒了!謝謝! – Azumiar

回答

1

的公式將是計算兩個點之間的距離,並獲得

//this would need to be recalulated on resize, but not doing it for demo 
 
var targetElem = document.querySelector("div.x span"); 
 
    box = targetElem.getBoundingClientRect(), 
 
    x = box.left + box.width/2, 
 
    y = box.top + box.height/2, 
 
    winBox = document.body.getBoundingClientRect(), 
 
    maxD = Math.sqrt(Math.pow(winBox.width/2, 2) + Math.pow(winBox.height/2, 2)); 
 
document.body.addEventListener("mousemove", function (evt) { 
 
    var diffX = Math.abs(evt.pageX-x), 
 
     diffY = Math.abs(evt.pageY-y), 
 
     distC = Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2)), 
 
     strength = Math.ceil(255 - (distC/maxD*255)).toString(16), 
 
     color = "#" + strength + strength + strength; 
 
    targetElem.style.backgroundColor = color;  
 
});
html, body { height: 100%; } 
 
div.x { position: absolute; top: 50%; left:50%; } 
 
span { display: inline-block; width: 20px; height: 20px; border-radius: 50%; border: 1px solid black; overflow: hidden; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<p>Test</p> 
 
<div class="x"><span>&nbsp;</span></div>

+0

謝謝!按照我的意願工作 – Azumiar

+0

當您將它們平方時,兩個距離的比例不會改變。在你的例子中計算平方根是多餘的,只需使用平方和。 – Blindman67