简体   繁体   English

在鼠标悬停时显示图像的某些部分

[英]Revealing portions of an image on mouseover

What is the best way to go about having a "fog of war" type thing where an image is blacked out, but then as the user mouses over the image an area around the cursor is revealed. 在图像被涂黑的情况下,使用“战争迷雾”类型的东西的最佳方法是什么,但随后当用户将鼠标悬停在图像上时,会显示光标周围的区域。 So probably some layer styled with CSS over an image, that as the user mouses over it becomes transparent and so the image can be seen in an area around the mouse, but the rest of the image is still blacked out. 因此,可能在图像上使用CSS设置了一些图层,当用户将鼠标悬停在图像上时,它变得透明,因此可以在鼠标周围的区域中看到图像,但图像的其余部分仍然是黑屏。

If you just want to use javascript and css to do this: 如果你只是想使用javascript和css来做到这一点:

  • Create a black image with a transparent hole in the middle 创建一个中间有透明孔的黑色图像
  • Use some javascript to get the mouse position 使用一些JavaScript来获取鼠标位置
  • Update the css to set the position of the fog image to the mouse pointer 更新css以将雾图像的位置设置为鼠标指针

You would have to make sure everything is layered correctly so that your image is under the fog image, and the fog image is under the rest of the content if this does not take up the entire browser window. 您必须确保所有内容都正确分层,以便您的图像位于雾图像下,如果不占用整个浏览器窗口,则雾图像位于其余内容之下。

I found this to be a very nice question, so for future visitors I will leave this as a reference: 我发现这是一个非常好的问题,因此对于未来的访问者,我将留下这个作为参考:

$(window).on('load', function () {
  var
    ctx = $('#canvas')[0].getContext('2d'),
    mouse = {x: -100, y: -100};

  // fill black
  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  // track mouse
  $('#canvas').on('mousemove.fog', function (evt) {
    mouse.x = evt.offsetX;
    mouse.y = evt.offsetY;
  });

  (function animloop(now) {
    var
      frame = webkitRequestAnimationFrame(animloop), // use a polyfill here
      x = mouse.x,
      y = mouse.y,
      r = 10,
      grad = ctx.createRadialGradient(x, y, 0, x, y, r);

    grad.addColorStop(0, "rgba(0, 0, 0, 255)");
    grad.addColorStop(1, "rgba(0, 0, 0, 0)");

    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillStyle = grad;
    ctx.arc(x, y, r, 0, 2 * Math.PI, true);
    ctx.fill();
  }(Date.now()));
});​

demo: http://jsfiddle.net/RUc5s/1/ 演示: http//jsfiddle.net/RUc5s/1/

On canvas, you could make a layer over the image that is partly transparent but the area near the cursor will be fully transparent. 在画布上,您可以在图像上创建一个部分透明的图层,但光标附近的区域将完全透明。 Layers don't really exist on canvas, but there are frameworks that allow you to do layers. 图层并不真正存在于画布上,但有一些框架可以让您进行图层处理。

on HTML/CSS, you could do "tiles" of the image that have 2 layers, an image below and a partly transparent PNG above. 在HTML / CSS上,您可以对图像的“图块”进行处理,图像有2层,下面是图像,上面是部分透明的PNG。 On hover, the PNG of the tile is set to display:none to reveal the image underneath. 在悬停时,图块的PNG设置为display:none以显示下面的图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM