使用画布或SVG在响应设计中进行图像遮蔽 [英] Image Masking With Canvas or SVG in Responsive Design

查看:131
本文介绍了使用画布或SVG在响应设计中进行图像遮蔽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在网站上呈现图像,就好像它们是不同的几何形状。例如,正常的正方形图像可以显示为六边形,圆形,五边形,八边形等。



这是一个响应式网站,图片将使用 max-width:100%; 进行样式设置,并根据其容器元素确定大小。



第一个想法是我创建了几个透明的PNG覆盖图像,每个所需的几何形状在透明区域&然后使用 z-index 在原始图像的顶部重叠遮罩。



有更好的方法与画布或SVG(甚至其他),并仍然允许图像和掩码均匀地调整为浏览器窗口调整大小?我需要考虑哪些性能方面的考虑?



最终的生产代码将使用jQuery,所以如果我需要这些方法,它会在那里。

解决方案

您可以将图像嵌入SVG内,并使用剪辑路径( Tinkerbin ):

 < svg xmlns =http:// www.w3.org/2000/svgxmlns:xlink =http://www.w3.org/1999/xlink
width =100%height =100%viewBox =0 0 100 100
< clipPath id =clipCircle>
< circle r =50cx =50cy =50/>
< / clipPath>
< clipPath id =clipTriangle>
< polygon points =0 0 50 100 100 0/>
< / clipPath>
< image clip-path =url(#clipCircle)preserveAspectRatio =nonewidth =100%height =100%xlink:href =http://upload.wikimedia.org/ wikipedia / commons / e / e5 / Catopsilia_pomona_3_by_kadavoor.jpg/>
< / svg>
< button onclick =document.getElementsByTagName('image')[0]
.setAttribute('clip-path','url(#clipTriangle)')&
更改剪辑路径
< / button>

点击按钮将圆形蒙版更改为三角形。


I'm attempting to render the images on a site as if they were different geometric shapes. For instance, a normally square image could be displayed as a hexagon, a circle, a pentagon, an octagon, etc.

This is a responsive site, meaning that the original images will be styled with max-width: 100%;, and they'll be sized depending on their container element.

The first thought that I had was to create several transparent PNG "overlay images" with each desired geometric shape "knocked out" in the transparent area & then use z-index to overlay the masks atop the original images.

Is there a better way to do this with canvas or SVG (or even something else) and still allow for the image and mask to evenly resize as the browser window resizes? What performance considerations do I need to account for?

The final production code will be using jQuery, so if I need it for any of these approaches, it will be there.

解决方案

You could embed the image inside SVG and use a clip path (Tinkerbin):

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" 
    width="100%" height="100%" viewBox="0 0 100 100">
  <clipPath id="clipCircle">
    <circle r="50" cx="50" cy="50"/>
  </clipPath>
  <clipPath id="clipTriangle">
    <polygon points="0 0 50 100 100 0"/>
  </clipPath>
  <image clip-path="url(#clipCircle)" preserveAspectRatio="none" width="100%" height="100%" xlink:href="http://upload.wikimedia.org/wikipedia/commons/e/e5/Catopsilia_pomona_3_by_kadavoor.jpg"/>
</svg>
<button onclick="document.getElementsByTagName('image')[0]
              .setAttribute('clip-path','url(#clipTriangle)')">
  change clip path
</button>

Click the button to change the circle mask to a triangular one.

这篇关于使用画布或SVG在响应设计中进行图像遮蔽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆