Javascript 从远处获得颜色

Javascript 从远处获得颜色,javascript,canvas,Javascript,Canvas,我在玩JavaScript/canvas,我希望我的对象颜色取决于从当前鼠标位置到其中心的距离。这是我当前的函数,它可以在每个mousemove事件中获取颜色: function getColorFromDistance(node1,node2){ var dist = getDist(node1,node2); //Getting distance; var cl = (Math.round(255/dist*255)).toString(16); //this needs t

我在玩JavaScript/canvas,我希望我的对象颜色取决于从当前鼠标位置到其中心的距离。这是我当前的函数,它可以在每个
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时,我会得到闪烁效果。
我需要一种方法让颜色的强度取决于距离,因此,鼠标离物体越远,其颜色越深,当鼠标位于物体中心时,其颜色完全为白色。你明白了。我只需要一个公式

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

//这需要在调整大小时重新设定,但在演示时不这样做
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”,函数(evt){
var diffX=数学绝对值(evt.pageX-x),
diffY=数学绝对值(evt.pageY-y),
distC=Math.sqrt(Math.pow(diffX,2)+Math.pow(diffY,2)),
强度=Math.ceil(255-(distC/maxD*255)).toString(16),
color=“#”+强度+强度+强度;
targetElem.style.backgroundColor=颜色;
});
html,正文{高度:100%;}
div.x{位置:绝对;顶部:50%;左侧:50%;}
span{显示:内联块;宽度:20px;高度:20px;边框半径:50%;边框:1px纯黑色;溢出:隐藏;}

试验


谢谢!工作如我所愿,两个距离的比例在平方时不变。在你的例子中,计算平方根是多余的,只需使用平方和。如果你想要一个彩色版本,你可以检查我的代码笔,它不是完美的,需要一些调整,但我认为它主要是你想要的。它使用css hls使事情更容易计算。