如果您正在執行復雜的分層繪製,則可以使用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