我在這個bug上拉了一下頭髮一段時間。我想在畫布的三個部分渲染圖像,而不允許它們重疊。基本上,我想用canvas.getContext('2d').clip()
來保持圖像分離。但是,剪輯僅適用於在繪製圖像後調用canvas.getContext('2d').beginPath()
。爲什麼javascript canvas2d裁剪需要路徑?
所以這不工作(沒有剪輯應用):
this.draw=function(image, cx, cy, width, height, clip){
var ctx = this.canvas.getContext('2d');
ctx.save();
ctx.rect(clip.x, clip.y, clip.width, clip.height);
ctx.clip();
ctx.fillStyle = "black";
ctx.fillRect(clip.x, clip.y, clip.width, clip.height);
ctx.drawImage(image,cx-width/2,cy-height/2,width,height);
ctx.restore();
return this;
};
但這:
this.draw=function(image, cx, cy, width, height, clip){
var ctx = this.canvas.getContext('2d');
ctx.save();
ctx.rect(clip.x, clip.y, clip.width, clip.height);
ctx.clip();
ctx.fillStyle = "black";
ctx.fillRect(clip.x, clip.y, clip.width, clip.height);
ctx.drawImage(image,cx-width/2, cy-height/2,width,height);
ctx.beginPath();// <------WITCHCRAFT
ctx.restore();
return this;
};
這是我發現了一個總的事故beginPath()
修復的問題,我不知道爲什麼。任何人都可以向我解釋這個嗎?
不是巫術,這是你告訴上下文的方式,你開始一條新的道路,並完成舊的道路。順便說一句,beginPath應該在你創建一個路徑之前去執行(就在你的代碼中'ctx.save()'之後)。只是運氣它的工作原理,因爲如果你使用ctx.arc而不是fillRect,它會將弧添加到剪輯中。 – Blindman67
我仍然對[rect()](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rect)的文檔感到困惑,它說子路徑是標記爲關閉。另外,如果我用'ctx.arc(256,256,512,0,3.1416 * 2,true);'替換fillRect行,裁剪仍然有效(512x512畫布)。公平地說,如果我將它移動到save()後面,它仍然可以工作。 – Kenkron
在很大程度上,我很困惑beginPath()似乎穿越時空。它不能用於剪切路徑,因爲已經完成了。它不能用於圖像,因爲這也是做的。就好像剪輯指令只在路徑啓動後才應用,但一旦它啓動,它可以追溯剪輯自剪輯調用後已經繪製的圖像。 – Kenkron