从远处获取颜色

时间:2016-07-29 17:54:53

标签: 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 to be a propper formula
    return "#" + cl + cl + cl; //converting to hex
}

目前,当距离达到255时,我会收到眨眼效果。 我需要一种方法来获得颜色强度取决于距离,以便进一步的鼠标远离物体,它越暗,当鼠标在物体中心时它的全白。你明白了。我只需要式

1 个答案:

答案 0 :(得分:1)

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



ID  Aisle   OddEven Bay Size    Y-Axis
1   A1      Even    14  10      100
2   A1      Even    16  10      110
3   A1      Even    20  10      120
4   A1      Even    26  5       150
5   A1      Even    28  5       155
6   A1      Even    32  5       160
7   A1      Odd     13  10      100
8   A1      Odd     17  10      110
9   A1      Odd     19  10      120
10  A1      Odd     23  5       150
11  A1      Odd     25  5       155
12  A1      Odd     29  5       160

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