简体   繁体   English

如何在javascript中叠加图像?

[英]How to overlay images in javascript?

I need to solve the following problem. 我需要解决以下问题。

I have two (or more) .PNG images of the same dimensions. 我有两个(或更多)相同尺寸的.PNG图像。 Each PNG image is created with transparent background color. 每个PNG图像都使用透明背景颜色创建。

I need to display img1 and upon it img2, so in places where img2 has trancparent color, img1 will be seen. 我需要显示img1并在其上显示img2,所以在img2具有trancparent颜色的地方,将会看到img1。

For example: img1 upper part filled with transparent color and a cow on down part. 例如:img1上部填充透明色,牛下部填充。 img2 upper part contains clouds and downpart filled with transparent color. img2上半部分包含云,下部填充透明色。

I want to combine these two images and see clouds above the cow. 我想把这两个图像结合起来,看看母牛上面的云。

I understand that I need to use some filter when displaying both images, but not sure which one and what parameters of it to use. 我知道在显示两个图像时我需要使用一些过滤器,但不确定使用哪个过滤器和哪个参数。

Something like this should work (using just HTML/CSS): 这样的东西应该工作(只使用HTML / CSS):

HTML: HTML:

<div class="imageWrapper">
  <img class="overlayImage" src="cow.png">
  <img class="overlayImage" src="clouds.png">
  <img class="overlayImage" src="downpart.png">
</div>

CSS: CSS:

.imageWrapper {
  position: relative;
}
.overlayImage {
  position: absolute;
  top: 0;
  left: 0;
}

Keep in mind that IE6 does not handle transparency in PNGs very well. 请记住,IE6不能很好地处理PNG中的透明度。 If you need it to work in IE6, you will need to apply the filters you mentioned. 如果您需要它在IE6中工作,您将需要应用您提到的过滤器。 This procedure is detailed here . 此过程详述此处

You don't need to use any sort of filter ( except in IE6 ). 您不需要使用任何类型的过滤器( IE6除外 )。

You can simply place to <img> elements on top of each-other, using CSS position: absolute to make both elements occupy the same area. 你可以简单地将<img>元素放在彼此之上,使用CSS position: absolute来使两个元素占据相同的区域。

In IE6, you'll need an AlphaImageLoader filter simply to display the PNGs with transparency 在IE6中,您只需要一个AlphaImageLoader过滤器来显示具有透明度的PNG

If you are using jquery try this in any browser 如果您正在使用jquery,请在任何浏览器中尝试此操作

<script>
$(function () {
    var position = $("#i1").offset();
    $('#i2').css({ position:'absolute', top:position.top, left: position.left});
});
</script>
<img id='i1' src='images/zap_ring.png' />
<img id='i2' src='images/zap_ring_hover.png' />

and adjust top & left values 并调整topleft

$('#i2').css({ position:'absolute', top:position.top-10, left: position.left+5});

You can try setting their .style.position to "absolute", give them the same coordinates with left and top (or right or bottom), and then change their z-index. 你可以尝试将他们的.style.position设置为“absolute”,给它们左边和顶部(或右边或底部)相同的坐标,然后改变它们的z-index。 Although it's quite dirty, and maybe it doesn't work well with your page, but I can't think of another solution. 虽然它很脏,也许它对你的页面效果不好,但我想不出另一个解决方案。

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

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