HTML5从先前绘制的笔划中切出圆圈 [英] HTML5 Cut out circle from previous drawn strokes

查看:44
本文介绍了HTML5从先前绘制的笔划中切出圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在html5中的先前绘制的画布上切出一个圆?

How can you cut out a circle on a previous drawn canvas in html5?

我尝试将其填充为透明,但是当然不起作用,我可以用一种颜色填充它,但是我真的需要将其从画布上切下来以露出下面的层.

I tried filling it transparent, and of course it did not work, I can fill it with a color but I really need it to be cut out of the canvas revealing the layer beneath.

这是我尝试过的.

  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();

推荐答案

您可以使用合成对画布下面的图像进行显示".

You can use compositing to do a 'reveal' of an image underneath the canvas.

  • 使用CSS定位将画布直接定位在图像上.
  • 用纯色填充顶部画布.
  • 收听鼠标按下事件.
  • 在事件处理程序中,将"compositing"设置为"destination-out",它将使用任何新图形切出"任何现有像素.
  • 在画布上绘图(使下面的img可以显示出新绘图的绘制位置.

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>

这篇关于HTML5从先前绘制的笔划中切出圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆