2016-07-29 132 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