简体   繁体   English

如何使用HTML 5画布仅绘制图像的圆形部分?

[英]How to draw only a circular part of an image with HTML 5 canvas?

How can I draw only a circular part of an image using HTML 5 canvas? 如何使用HTML 5画布仅绘制图像的圆形部分?

For instance, to take a photo and only draw the face inside the canvas. 例如,拍摄照片并仅在画布内绘制脸部。

The way to achieve this is to use clip to define a clipping region: 实现此目的的方法是使用clip来定义剪切区域:

var ctx;
var canvas;

var img = new Image();

img.onload = function() {

    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');


    ctx.beginPath();
    ctx.arc(100, 100, 60, 0, 6.28, false); //draw the circle
    ctx.clip(); //call the clip method so the next render is clipped in last path
    ctx.stroke();
    ctx.closePath();
    ctx.drawImage(img, -190, 0);
};

img.src = "http://www.antiquiet.com/wp-content/uploads/2011/03/Free-Trapper_Remasters_The-Kills-467x311.jpg";

You can see a working fiddle here: http://jsfiddle.net/hJS5B/47/ 你可以在这里看到一个工作小提琴: http//jsfiddle.net/hJS5B/47/

Code reused from my answer to this question: Draw multiple circles filled with image content 从我对这个问题的回答中重复使用的代码: 绘制多个带有图像内容的圆圈

As I found this thread long before I found the solution for what I was searching for: the code above works great. 在我找到我正在寻找的解决方案之前很久就找到了这个帖子:上面的代码效果很好。 But if you want to draw circular areas of an image again and again, eg in an onmouseup event, then you have to save and restore the state of the context. 但是,如果要反复绘制图像的圆形区域,例如在onmouseup事件中,则必须保存并恢复上下文的状态。 More is explained here: Can you have multiple clipping regions in an HTML Canvas? 这里解释了更多: 你可以在HTML Canvas中有多个剪辑区域吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM