简体   繁体   中英

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.

If you just want to use javascript and css to do this:

  • Create a black image with a transparent hole in the middle
  • Use some javascript to get the mouse position
  • Update the css to set the position of the fog image to the mouse pointer

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/

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. On hover, the PNG of the tile is set to display:none to reveal the image underneath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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