如果您正在执行复杂的分层绘制,则可以使用globalCompositeOperation在另一个临时画布中模拟剪切。然后,您可以使用drawImage将临时画布复制回原始画布。我不能保证这种方法的性能,但这是我知道得到你想要的唯一方法。
//set-up - probably only needs to be done once
var scratchCanvas = document.createElement('canvas');
scratchCanvas.width = 100;
scratchCanvas.height = 100;
var scratchCtx = scratchCanvas.getContext('2d');
//drawing code
scratchCtx.clearRect(0, 0, scratchCanvas.width, scratchCanvas.height);
scratchCtx.globalCompositeOperation = 'source-over'; //default
//Do whatever drawing you want. In your case, draw your image.
scratchCtx.drawImage(imageToCrop, ...);
//As long as we can represent our clipping region as a single path,
//we can perform our clipping by using a non-default composite operation.
//You can think of destination-in as "write alpha". It will not touch
//the color channel of the canvas, but will replace the alpha channel.
//(Actually, it will multiply the already drawn alpha with the alpha
//currently being drawn - meaning that things look good where two anti-
//aliased pixels overlap.)
//
//If you can't represent the clipping region as a single path, you can
//always draw your clip shape into yet another scratch canvas.
scratchCtx.fillStyle = '#fff'; //color doesn't matter, but we want full opacity
scratchCtx.globalCompositeOperation = 'destination-in';
scratchCtx.beginPath();
scratchCtx.arc(50, 50, 50, 0, 2 * Math.PI, true);
scratchCtx.closePath();
scratchCtx.fill();
//Now that we have a nice, cropped image, we can draw it in our
//actual canvas. We can even draw it over top existing pixels, and
//everything will look great!
ctx.drawImage(scratchCanvas, ...);
我们在临时画布中这样做的原因是,目标输入是一个非常具有破坏性的操作。如果你已经在主画布上绘制了一些东西(也许你在背景中放下了一个很好的渐变),然后想要绘制剪裁的图像,剪裁圆也会剪掉你已经绘制的所有东西。当然,如果你的特定情况比较简单(也许你想绘制的图像是一个剪辑图像),那么你可以放弃临时画布。
可以玩弄于my demo page不同的修剪模式。底行(带渐变)对你来说并不是太有用,但最上面的一行(与圆形和方形)更相关。
编辑
哎呦,我不小心forked your JSFiddle来演示该技术。
我也遇到了这个问题。我所做的就是在图像的相同位置绘制一个圆圈,在它后面,半径为1或2 px。保持颜色相似,然后去“反锯齿”图像剪辑。 – Automatico 2012-07-23 14:31:13