我有2层,我想在前层打洞让用户看到后层。为此,我在 Canvas 上画圆圈,将圆圈放在两层之间(不知道它的位置是否正确)。
为了演示目的,我分解了 3 层,并显示了 Canvas 。
我已经尝试了混合/ mask 的几种组合,但我在这里遗漏了一些东西,正在寻求帮助。
2层的canvas应该放在什么位置,应该做什么样的混合操作才能在前层打洞?
一个解决方案应该是告诉前层它应该在显示时使用 Canvas 作为 alpha 蒙版。
注意:背面层应保持不变。
这是解释布局的屏幕截图:
...和代码笔链接: Mask Effect
/***
** onclick(e)
*/
$( document ).click(function(e) {
var ctx = $("canvas")[0].getContext('2d');
var radius = Math.random() * 50 + 10;
ctx.beginPath();
ctx.arc(e.clientX, e.clientY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();
// ctx.globalCompositeOperation = 'screen';
// ctx.drawImage(ctx.canvas.toDataURL("image/png"),0,0); // debug: visualize
$('#front').css({
'mask-image':"url(" + ctx.canvas.toDataURL("image/png")+ ")",
'background-blend-mode':"screen",
'background-image':"url(" + ctx.canvas.toDataURL("image/png")+ ")"
});
最佳答案
路径的解决方案类似于:
var width = 300;
var height = 200;
var canvas = document.getElementById( "myCanvas" );
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FFFFFF";
ctx.fillRect( 0, 0, width, height );
canvas.onmousemove = function( e ){
ctx.clearRect( 0, 0, width, height );
// counter-clockwise path
ctx.fillStyle = "#FFFFFF";
ctx.beginPath();
ctx.moveTo( 0, 0 );
ctx.lineTo( 0, height );
ctx.lineTo( width, height );
ctx.lineTo( width, 0 );
ctx.closePath();
// clockwise path
ctx.arc( e.clientX, e.clientY, 20, 0, 2 * Math.PI, false);
ctx.fill();
};
#back {
position: absolute;
left: 0px;
top: 0px;
width: 300px;
height: 200px;
background: linear-gradient( to right, red , yellow);
z-index: 0;
}
#front {
position: absolute;
left: 0px;
top: 0px;
width: 300px;
height: 200px;
z-index: 1;
border: solid thin #000000;
}
<div id="back"></div>
<div id="front">
<canvas id="myCanvas" width="300" height="200"/>
</div>
看看这里了解为什么有效:Masking shapes in HTML5 canvas?
关于jquery - 如何在div中打洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935033/