如何让我的Javascript只显示一个以鼠标为中心的聚光灯?

时间:2016-03-22 22:38:17

标签: javascript css

website的顶部你可以看到我的动画在顶部,我无法让它显示一个以鼠标为中心的聚光灯以及文字阴影效果也以鼠标为中心。

我发现通过放大浏览器,中心问题是固定的,但如果可能的话,我宁愿不为访问者设置固定的缩放级别。

下面我附上了CSS,然后是我使用过的JavaScript:

CSS:

#text-shadow-box {
    position: relative;
    width: 100%;
    height: 350px;
    background: #666;
    overflow: hidden;
    cursor: none;
    border: 1px solid Black;
    -webkit-tap-highlight-color: rgba(0,0,0,0);
    -webkit-user-select: none;
}

#text-shadow-box div.wall {
    position: absolute;
    top: 175px;
    left: 0;
    width: 100%;
}

#tsb-text {
    margin: 0;
    color: #999;
    font-family: Helvetica, Arial, sans-serif;
    font-size: 80px;
    line-height: 1em;
    height: 1px;
    font-weight: bold;
    text-align: center;
}

div.wall div {
    position: absolute;
    background: #999;
    overflow: hidden;
    top: 150px;
    left: 0;
    height: 300px;
    width: 100%;
}

#tsb-spot {
    position: absolute;
    overflow: hidden;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url(/spotlight.png) top center;
}

JavaScript:

<script type="text/javascript" language="javascript" charset="utf-8">

var text;
var spot;

///window.onload = init;
init();

function init() {
text = document.getElementById('tsb-text');
spot = document.getElementById('tsb-spot');

document.getElementById('text-shadow-box').onmousemove = onMouseMove;
document.getElementById('text-shadow-box').ontouchmove = function (e)    {e.preventDefault(); e.stopPropagation(); onMouseMove({clientX:     e.touches[0].clientX, clientY: e.touches[0].clientY});};

onMouseMove({clientX: 300, clientY: 200});
}


function onMouseMove(e) {
var xm = e.clientX - 300;
var ym = e.clientY - 175;
var d = Math.sqrt(xm*xm + ym*ym);
text.style.textShadow = -xm + 'px ' + -ym + 'px ' + (d / 5 + 10) + 'px  black';

xm = e.clientX - 600;
ym = e.clientY - 450;
spot.style.backgroundPosition = xm + 'px ' + ym + 'px';
}

</script>

1 个答案:

答案 0 :(得分:0)

根据您当前的实施,您正在使用图像作为聚光灯,在此行中找到:

background: url(http://www.zachstronaut.com/lab/text-shadow-box/spotlight.png) top center;

更好的实施方法是添加<canvas>元素,而不是您网站上的标题。您可以使用CanvasRenderingContext2D.createRadialGradient()创建聚光灯效果:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createRadialGradient

您还可以在此处看到我推荐的类似实现:

https://jsfiddle.net/4Ezkg/

http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/