image cropped as a triangle on webpage

允我心安 提交于 2019-12-11 10:32:47

问题


This is a real css-challenge, I don't think this is possible:

I've made some white css triangles. and when you hover on a triangle, the white triangle should change in a photo also cropped like a triangle. I've made a jsfiddle for it:

fiddleLink

Any help appreciated


回答1:


You can use svg to achieve this effect: http://jsfiddle.net/xTd6Y/4/

<div id="image-wrapper">
    <svg id="svg-1" class="clip-svg">
        <rect class='svg-background' width="300" height="300" fill="#ffffff" />
        <image id="img-1" class='svg-image' width="300" height="300" xlink:href="http://lorempixel.com/300/300" />
    </svg>
    <svg id="svg-2" class="clip-svg">
        <rect class='svg-background' width="300" height="300" fill="#ffffff" />
        <image id="img-2" class='svg-image' width="300" height="300" xlink:href="http://lorempixel.com/300/301" />
    </svg>
    <svg id="svg-3" class="clip-svg">
        <rect class='svg-background' width="300" height="300" fill="#ffffff" />
        <image id="img-3" class='svg-image' width="300" height="300" xlink:href="http://lorempixel.com/300/302" />
    </svg>
</div>
<svg id="svg-defs">
    <defs>
        <clipPath id="clip-triangle">
            <polygon points="0, 200 100, 0 200, 200"/>
        </clipPath>
    </defs>
</svg>

css

body {
    background-color: #e0e0e0;
}
#image-wrapper {
    position: relative;
}
.svg-background, .svg-image {
    clip-path: url(#clip-triangle);
}
.svg-image {
    visibility: hidden;
}
.clip-svg .svg-image:hover {
    visibility: inherit;
}

/* size and positioning */
 svg.clip-svg {
    position: absolute;
    height: 250px;
    width: 250px;
}
#svg-1 {
    top: 110px;
    left: 50px;
}
#svg-2 {
    top: 40px;
    left: 140px;
}
#svg-3 {
    top: 160px;
    left: 250px;
}

The clipping path is defined in svg#svg-defs, and can be set to whatever you like.

Image attributes are visible to / accessible by js and css. You can apply the clipping path to any html element with css of

myElement {
    clip-path: url(#clip-triangle);
}

but this is only reliable on firefox so far as I can tell.

Note: solution only tested on FF and chrome

note: small edit to move :hover from the svg to the embedded image, to correct problem with hover triggered outside clip area



来源:https://stackoverflow.com/questions/17638356/image-cropped-as-a-triangle-on-webpage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!