SVG 使用紀錄 in Blazor

html5, SVG in Blazor

引言

剛好有在 html 繪圖的需求,滿足的方案有 canvas 與 SVG。經試用 canvas 適合開發像小畫家、pohotshop 徒手繪圖(drawing)的應用,這不適合我們。SVG 比較適合製作圖表(chart,graph)這比較適合。

沒圖沒真像

船舶停靠港口路徑簡化示意圖。

程式碼

<!DOCTYPE html>
<html>
<body>

<svg width="400" height="400">
  <!-- 邊界:座標系請自行轉換 -->
  <rect x="0" y="0" width="400" height="400" style="stroke:darkgrey;stroke-width:4;fill:lightblue;" />
  <text x="0" y="12" fill="black" style="text-anchor:start; font-family:微軟正黑體; font-size:12px">[0,0]</text>
  <text x="400" y="397" fill="black" style="text-anchor:end; font-family:微軟正黑體; font-size:12px">[400,400]</text>
  
  <!-- 港口:以方形表示 -->  
  <rect x="180" y="180" width="40" height="40" style="stroke:black;stroke-width:2;fill:none;" />
  <rect x="190" y="240" width="30" height="20" style="stroke:black;stroke-width:2;fill:none;" />
  
  <!-- 船舶:以點表示 -->
  <rect x="140" y="140" width="4" height="4" style="fill:red;" />
  <text x="140" y="137" fill="red" style="text-anchor:start; font-family:微軟正黑體; font-size:12px">台灣之星郵輪</text>

  <rect x="120" y="120" width="4" height="4" style="fill:blue;" />
  <text x="120" y="117" fill="blue" style="text-anchor:start; font-family:微軟正黑體; font-size:12px">台灣之星郵輪</text>
  
  <rect x="100" y="100" width="4" height="4" style="fill:green;" />  
  <text x="100" y="97" fill="green" style="text-anchor:start; font-family:微軟正黑體; font-size:12px">台灣之星郵輪</text>
		
Sorry, your browser does not support inline SVG.
</svg>

</body>
</html>

在SVG顯示文字的標籤是<text/>這剛好與 Blaozr 的 <text/> 衝突。解決方案就是用 Blaozr <text/> 包括住 SVG <text/>,如下:

FooSvgWidget.razor
<svg width="@CANVAS_LENGTH" height="@CANVAS_LENGTH">
...略...

<!-- 船舶(最新位罝) -->
@if (ShipList != null)
{
  foreach (var ship in ShipList.LivePositions)
  {
    //# 船舶座標在可視範圍內才繪製。(畫了也看不到沒意義,只是浪費運算量)
    double x_ = ship.VesselPosition.PositionLon;
    double y_ = ship.VesselPosition.PositionLat;
    (double x, double y) = ConvertCoordinatesXY(x_, y_);
    
    <text> @* <--- 這是 Blazor <text/>  *@
      <rect x="@(x-2)" y="@(y-2)" width="4" height="4" style="fill:red;" />
      <text x="@(x-2)" y="@(y-5)" fill="red" style="text-anchor:start; font-family:微軟正黑體; font-size:12px">@(ship.VesselName.En)</text>
    </text>
  }
}
</svg>

@code {
  [Parameter] public TdxShipLivePosition? ShipList { get; set; } = null;
}

Last updated