目標
我試圖通過演算法復制這種效果:

這是我正在從事的一個專案,我需要對不同種類的比薩進行風格化的可視化。影像顯示了瑪格麗特(番茄底,馬蘇里拉奶酪和羅勒在上面)。
我需要遵守的規則:
- 每個“層”由均勻定位的物件組成,帶有筆劃并填充有圖案(共享坐標)
- 層需要覆寫較低的層
方法
為了實作均勻分布,我使用Poisson-Disc 采樣。
我選擇 SVG 是因為我需要結果在瀏覽器中可見并生成這個服務器端。
為了效率和簡單性——因為查看尺寸會更小——我決定用<use>元素來參考一個物件,并只通過旋轉來改變它,而不是樣本。
嘗試
我嘗試的每種方法都走到了死胡同:
創建一個
<clipPath>充滿<use>元素的剪輯背景。這不允許我在我需要的剪切區域周圍添加筆觸。一種解決方法是使用feMorphology 過濾器,但這似乎對客戶端來說會產生不必要的成本。第二種解決方法似乎是:
將元素分組并使用該組兩次:一次在 a 中
<clipPath>用于剪切圖案背景,一次直接在畫布上添加筆劃。This does not work as
<g>elements are unsupported in web browsers due to completely arbitrary reasons (it does work in Inkscape, however, which I used for the proof-of-concept). A workaround would be to use two copies of all the<use>elements, but that would essentially double the file size.Grouping the elements and applying a fill with SVG patterns.
This does not work as since we create the distribution using
<use>elements, the pattern looks identical in every instance. Moreover, I cannot rotate the objects, as the pattern would get rotated too. A workaround would be not to use<use>, but that would create the same problem as in point 2.
uj5u.com熱心網友回復:
這些方法不起作用,因為模式會受到應用于同一形狀的任何變換的影響。
在下面的解決方案中,我們創建了一整層成分 ( id="basil-layer")。然后使用該圖層首先繪制成分輪廓(筆觸)。然后我們使用從同一層創建的蒙版在輪廓頂部繪制陰影。
您需要為每種成分重復此程序。
有關代碼內部發生的事情的更多檔案。
<svg width="600" height="400">
<defs>
<pattern id="diagonalHatch" patternUnits="userSpaceOnUse" viewBox="0 0 4 4" width="16" height="16">
<rect fill="black" width="4" height="4"/>
<path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2"
style="stroke:green; stroke-width:0.5" />
</pattern>
<!-- Definition for a leaf of basil -->
<ellipse id="basil" cx="0" cy="0" rx="60" ry="30"/>
<!-- A layer of N pieces of basil -->
<g id="basil-layer">
<use xlink:href="#basil" transform="translate(300,200)"/>
<use xlink:href="#basil" transform="translate(400,150) rotate(45)"/>
<use xlink:href="#basil" transform="translate(450,200) rotate(110)"/>
</g>
<!-- A mask that consists of all the pieces of basil -->
<!-- The fill is white to keep the *insides* of the basil shape.
And we stroke with black so that this mask doesn't hide any of the
green stroke outline of the leaf, when use this mask to lay down
the hatch pattern on top of the drawn basil leaves. -->
<mask id="basil-layer-mask">
<use xlink:href="#basil-layer" fill="white" stroke="black" stroke-width="2"/>
</mask>
</defs>
<!-- Fill SVG with a black background -->
<rect width="100%" height="100%" fill="black"/>
<!-- Draw all the basil pieces with a black fill and a green outline -->
<use xlink:href="#basil-layer" fill="black" stroke="green" stroke-width="2"/>
<!-- Finally draw the basil layer hatching.
This is a whole-SVG sized rectangle of hatching masked by the basil layer mask -->
<rect width="100%" height="100%" fill="url(#diagonalHatch)" mask="url(#basil-layer-mask)"/>
</svg>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/346441.html
標籤:svg
