如何在html5中的先前绘制的画布上剪切圆圈?
我试着将它填充透明,当然它不起作用,我可以用一种颜色填充它,但我真的需要它从画布上切下来,露出下面的层。
这就是我的尝试。
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = "rgba(0, 0, 0, 0)";
context.fill();
和
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = "rgba(255, 255, 255, 1)";
context.fill();
答案 0 :(得分:0)
您可以使用合成来对画布下方的图像进行“显示”。
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var radius=30;
ctx.fillStyle='skyblue';
ctx.fillRect(0,0,canvas.width,canvas.height);
function cut(x,y,radius){
ctx.save();
ctx.globalCompositeOperation='destination-out';
ctx.beginPath();
ctx.arc(x,y,radius, 0, 2 * Math.PI, false);
ctx.fill();
ctx.restore();
}
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
x=parseInt(e.clientX-offsetX);
y=parseInt(e.clientY-offsetY);
cut(x,y,radius);
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
body{ background-color: ivory; }
#canvas{border:1px solid red;}
#wrapper{position:relative;}
#bk,#canvas{position:absolute;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click on the canvas to cut a circle<br>and reveal the img underneath.</h4>
<img id=bk src='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/KoolAidMan.png'>
<canvas id="canvas" width=300 height=300></canvas>