2014-10-13 2 views
0

나는 정사각형 문맥을 가지고 있으며 캔버스를 원으로 자르려고합니다. clip()을 사용하여 시도했지만 캔버스 위에 물건을 그려 넣기 전에 작동합니다. 모든 것이 그려진 후에 캔버스를자를 방법이 있습니까?html 캔버스의 원형 자르기

답변

1

context.globalCompositeOperation='destination-in'을 사용하면 "사후"클립을 수행 할 수 있습니다.

enter image description here

예제 코드와 데모 :

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>

+0

신난다! 정확히 내가 무엇을 찾고 있었는지 – Siva

관련 문제