html画布的圆形裁剪 [英] Circular crop for html canvas

查看:379
本文介绍了html画布的圆形裁剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方形的上下文,我试图剪切的画布成一个圆圈。我试过使用clip(),但这只有在工作之前绘制到画布上。

I have a square context and I am trying to "cut" the canvas into a circle. I've tried using clip() but this only works prior to having things drawn onto the canvas. Is there any way to crop a canvas after everything has been drawn on it?

推荐答案

您可以使用 context.globalCompositeOperation ='destination-in'执行事后剪辑。

You can use context.globalCompositeOperation='destination-in' to do an "after the fact" clip.

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/desert1.jpg";
function start(){
  var cw,ch;
  cw=canvas.width=img.width;
  ch=canvas.height=img.height;
  ctx.drawImage(img,0,0);
  ctx.globalCompositeOperation='destination-in';
  ctx.beginPath();
  ctx.arc(cw/2,ch/2,ch/2,0,Math.PI*2);
  ctx.closePath();
  ctx.fill();
}

body{ background-color: ivory; }
canvas{border:1px solid red;}

Original Image:<br>
<img src='https://dl.dropboxusercontent.com/u/139992952/stackoverflow/desert1.jpg'><br>
Clip existing content into circle with Compositing<br>
<canvas id="canvas" width=300 height=300></canvas>

这篇关于html画布的圆形裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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