2

Here's a related image: What I want to achieve is on the right.

I want to achieve something like what's pictured on the right side of my image. But I also have a parent container that has a background image of its own, instead of a solid color.

Any advice?

EDIT: Forgot to add, cross-browser compatibility is important. (Or atleast Firefox).

4

4 回答 4

5

I can only think of one pure CSS solution and it is simply insane.

Let's say your image has a width of 100px. You'll have to create a div that's 100px wide and give it 100 children that are each 1px wide, that each have the same background (positioned accordingly) and that each have an opacity from 0 (the first child) to .99 (the last child).

Personally, I think it's crazy and I'd never use this method.

Rory O'Kane came with a nice and clean solution and I also have another idea which involves JavaScript.

Basically, the idea is that you use a canvas element (support), draw your image on it, loop through its pixels and adjust the alpha for each.

demo

(scroll down to see the result)

Relevant HTML:

<div class='parent'>
  <canvas id='c' width='575' height='431'></canvas>
</div>

Relevant CSS (setting the background image on the parent)

.parent {
  background: url(parent-background.jpg);
}

JavaScript:

window.onload = function() {
  var c = document.getElementById('c'), 
      ctxt = c.getContext('2d'), 
      img = new Image();
  
  img.onload = function() {
    ctxt.drawImage(img, 0, 0);
    var imageData = ctxt.getImageData(0, 0, 575, 431);
    for(var i = 0, n = imageData.data.length; i < n; i += 4) {
      imageData.data[i + 3] = 255*((i/4)%575)/575;
    }
    ctxt.putImageData(imageData, 0, 0);
  };
  /* images drawn onto the canvas must be hosted on the same web server 
  with the same domain as the code executing it */
  /* or they can be encoded like in the demo */
  img.src = 'image-drawn-on-canvas.jpg';
};
于 2012-09-30T14:44:38.330 回答
1

check these out maybe helpful

DEMO 1

DEMO 2

于 2012-09-30T00:38:44.910 回答
1

Ignoring possible CSS-only methods, you can make the image a PNG with the transparent gradient built in to the image’s alpha channel. All browsers support PNG transparency, except for IE 6 and below. Here’s what your sample image would look like as a PNG with a transparent gradient (try putting this image against other backgrounds):

PNG image with transparent gradient

If the images are user-submitted so you can’t add the gradient ahead of time, you could create and store a gradient-added version of each image at the time that the user uploads them.

于 2012-09-30T06:32:20.770 回答
1

CSS only method:

https://gist.github.com/3750808

于 2012-10-01T18:00:51.200 回答