简体   繁体   English

在响应设计中使用Canvas或SVG进行图像蒙版

[英]Image Masking With Canvas or SVG in Responsive Design

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%; 这是一个响应式网站,这意味着原始图像的样式将设置为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. 我首先想到的是创建几个透明的PNG“重叠图像”,并在透明区域中将每个所需的几何形状“敲掉”,然后使用z-index将遮罩覆盖在原始图像之上。

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? 有没有更好的方法可以使用canvas或SVG(或什至其他东西)做到这一点,并且仍然允许图像和遮罩随着浏览器窗口大小的调整而均匀地调整大小? 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. 最终的生产代码将使用jQuery,因此,如果我需要这些方法中的任何一种,都可以使用它。

You could embed the image inside SVG and use a clip path ( Tinkerbin ): 您可以将图像嵌入SVG并使用剪切路径( 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. 单击按钮将圆形蒙版更改为三角形。

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

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