从远处获取色彩

Get color from distance

本文关键字:色彩 获取      更新时间:2023-09-26

我在玩JavaScript/画布,我希望我的对象颜色取决于从当前鼠标位置到其中心的距离。这是我当前的函数,它为每个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时,我会得到眨眼的效果。我需要一种方法来获得取决于距离的颜色强度,这样鼠标离物体越远,它就越暗,当鼠标在物体中心时,它就完全是白色的。好吧,你明白了。我只需要公式

公式将计算两点之间的距离,并根据最大值(画布/窗口的宽度)获得百分比

//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>