簡體   English   中英

html 畫布剪輯,但帶有圖像

[英]html canvas clip but with an image

我一直在使用 html 畫布合成,試圖用蒙版剪輯圖案。

我的主要問題是我的面具來自最外邊界內帶有透明膠片的 svg。 我希望從最外邊的整個內部都填充圖案。

以這個 SVG 為例,您可以看到有一個像素邊框,然后是一些透明度,然后是一個不透明的紅色內部斑點。 我所做的合成按照文檔說的那樣工作,單個像素邊框和紅色內部部分拾取了我想要遮罩成這種形狀的圖案。 問題是我想從單個像素邊界開始掩蓋整個內臟。

這就是我認為剪輯可能會有所幫助的地方。 但似乎剪輯只適用於手動繪制的路徑,而不是來自 svg 的路徑(至少我知道)。

有沒有辦法完成我想要做的事情?

問候, 詹姆斯

Path2D 構造函數接受一個 SVG 路徑數據參數,它將解析為 SVG <path>元素的d屬性。

然后,您可以通過clip()方法使用此 Path2D 對象:

 (async () => { // fetch the svg's path-data const markup = await fetch("https://upload.wikimedia.org/wikipedia/commons/7/76/Autism_spectrum_infinity_awareness_symbol.svg").then(resp => resp.ok && resp.text()); const doc = new DOMParser().parseFromString(markup, "image/svg+xml"); const pathData = doc.querySelector("[d]").getAttribute("d"); // build our Path2D object and use it const path = new Path2D(pathData); const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); ctx.clip(path); // draw something that will get clipped const rad = 30; for(let y = 0; y < canvas.height; y += rad * 2 ) { for(let x = 0; x < canvas.width; x += rad * 2 ) { ctx.moveTo(x+rad, y); ctx.arc(x, y, rad, 0, Math.PI*2); } } ctx.fillStyle = "red"; ctx.fill(); })().catch(console.error);
 <canvas width="792" height="612"></canvas>

如果您需要轉換此路徑數據(例如縮放或旋轉),那么您可以創建第二個 Path2D 對象,並使用其.addPath(path, matrix)方法來執行此操作:

 // same as above, but smaller (async () => { const markup = await fetch("https://upload.wikimedia.org/wikipedia/commons/7/76/Autism_spectrum_infinity_awareness_symbol.svg").then(resp => resp.ok && resp.text()); const doc = new DOMParser().parseFromString(markup, "image/svg+xml"); const pathData = doc.querySelector("[d]").getAttribute("d"); const originalPath = new Path2D(pathData); const path = new Path2D(); // scale by 0.5 path.addPath(originalPath, { a: 0.5, d: 0.5 }); const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); ctx.clip(path); // draw something that will get clipped const rad = 15; for(let y = 0; y < canvas.height; y += rad * 2 ) { for(let x = 0; x < canvas.width; x += rad * 2 ) { ctx.moveTo(x+rad, y); ctx.arc(x, y, rad, 0, Math.PI*2); } } ctx.fillStyle = "red"; ctx.fill(); })().catch(console.error);
 <canvas width="396" height="306"></canvas>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM