裁剪图像以形成椭圆形(居中图像) [英] Clip an image to form an oval (centered image)
问题描述
我正在尝试将图像剪切成形状,然后在画布上绘制它们。我很好奇如何裁剪图像以使其恢复为椭圆形。我会使用类似 arc()
或 bezierCurves()
之类的东西吗?
I am trying to clip images into shapes and then draw them on canvas. I am curious how would I clip an image to return it as an oval shape. Would I use something like arc()
or bezierCurves()
?
推荐答案
您可以通过缩放圆形(圆形==圆弧)来绘制椭圆,如下所示:
// Make an oval that's twice as tall as its width
// and draw it at the center of the canvas
var scaleX=1;
var scaleY=2;
var radius=canvas.width;
ctx.scale(scaleX,scaleY);
ctx.arc(canvas.width/scaleX/2,canvas.height/scaleY/2,radius,0,Math.PI*2);
ctx.fill();
然后,您可以使用合成绘制图像,使其仅显示在椭圆形内部。 / strong>
Then you can use compositing to draw the image so it only appears inside the oval.
这是通过 context.globalCompositeOperation ='source-atop'
完成的,这会导致出现新的像素仅当它们与现有的不透明像素重叠时:
This is done with context.globalCompositeOperation='source-atop'
which causes new pixels to appear only if they overlap existing opaque pixels:
以一点数学比率折腾,甚至可以使椭圆形显示最大的图像量...
Toss in a little bit of math ratios and you can even get the oval to display the maximum amount of image...
示例代码和演示:
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/multple/kidwallpaper.jpg";
function start(){
// resize the canvas to equal the image size
var iw=img.width;
var ih=img.height;
cw=canvas.width=iw;
ch=canvas.height=ih;
// calculate the scaling needed to max the display of the image
// inside the oval
if(iw>ih){
var scaleX=iw/ih
var scaleY=1;
var r=ih/2;
}else{
var scaleX=1;
var scaleY=ih/iw;
var r=iw/2;
}
// scale so the circle (arc) becomes an oval
ctx.scale(scaleX,scaleY);
ctx.arc(cw/scaleX/2,ch/scaleY/2,r,0,Math.PI*2);
ctx.fill();
// undo the scaling
ctx.scale(1/scaleX,1/scaleY);
// draw the image centered inside the oval using compositing
ctx.globalCompositeOperation='source-atop';
ctx.drawImage(img,cw/2-img.width/2,ch/2-img.height/2);
ctx.globalCompositeOperation='source-atop';
}
body{ background-color: black; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
这篇关于裁剪图像以形成椭圆形(居中图像)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!