使用CSS在黑色覆盖层上添加模板 - 反向圆形遮罩

3

我有一张iPhone截图(背景为jpeg),上面覆盖了一层黑色遮罩(带有一定的透明度)。我需要动态添加一个圆形模板,具有特定的半径,以覆盖黑色背景,使其更加清晰可见。

所谓动态,是指可以根据需要设置x和y坐标。

CSS

#img {
    display: block;
    width: 480px;
    height: 720px;
    background: url('iphone.jpg') no-repeat center center
}
div.overlay {
    display: block;
    width: 480px;
    height: 720px;
    background-color: #000;
    filter: alpha(opacity=65);
    -khtml-opacity: 0.65;
    -moz-opacity: 0.65;
    opacity: 0.65;
}
div.stencil {
    /* ??? */
}

HTML

<div id="img">
    <div class="overlay"></div>
    <div class="stencil"></div>
</div>

这是我尝试实现的一个例子:

带有黑色覆盖层的iPhone截图

请问能够实现吗?谢谢。

2
请看这个链接:http://thenittygritty.co/css-masking - Pevara
1个回答

3
我将展示给您两个示例,一个使用DIV作为覆盖层,另一个使用HTML5 canvas

DIV覆盖:

演示

我建议创建一个带有四个1/4圆孔的大方形不透明.png文件,每个角都有一个。然后将其设置为.overlay的重复背景。之后通过设置该DIV的background-position: Xpx, Ypx;,您将完全定位任何想要的区域,并且位于精确的中心位置。

HTML代码:

<div id="img">
    <div class="overlay"></div>
</div>

CSS:

#img {    
    position:relative;
    overflow:hidden;
    width: 199px;
    height: 390px;
    background: url('iphone.jpg') no-repeat center center;
}

.overlay {
    position:absolute;
    height:100%;
    width:100%;
    background:url(http://i.stack.imgur.com/ohb0l.png);
    /* PLAY HERE: */
    background-position: 120px 130px;
}

在此输入图片描述


否则使用canvas :)

globalCompositeOperation = 'destination-out'; 就可以实现:

下面的代码将在图像上放置一个蒙版并从蒙版中移除一个 圆弧

在线演示

HTML:

<canvas id="iphone"></canvas>

JS:

var cirsleSize = 30 ,  // circle radius
    circleX = 120 ,    // X pos
    circleY = 130 ;    // Y pos

// ---------------------------------------------

var canvas = document.getElementById('iphone'),
    ctx = canvas.getContext('2d'),
    img = new Image();

canvas.height=390;
canvas.width=199;

img.onload = function() {

   ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
   ctx.fillStyle = "rgba(255,255,255,0)";
   ctx.fillRect(0, 0, canvas.width, canvas.height);
   var mask = document.createElement('canvas');
   mask.width = canvas.width;
   mask.height = canvas.height;
   var maskCtx = mask.getContext('2d');
   maskCtx.fillStyle = "rgba(0,0,0,0.6)";
   maskCtx.fillRect(0, 0, mask.width, mask.height);
   maskCtx.globalCompositeOperation = 'destination-out';
   maskCtx.arc(circleX, circleY, cirsleSize, 0, 2*Math.PI);
   maskCtx.fill();
   ctx.drawImage(mask,0,0);
      
};

img.src = 'iphone_199x390.jpg';

1
这将是一个很好的开始。谢谢! - Andres SK
1
@Andufo 谢谢!(如果您不介意,我会为您的问题添加html5canvas标签,以便其他人更容易地找到您的问题!)祝编码愉快! - Roko C. Buljan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接