# Canvas fundamentals

Draw directly in C# with Xui's Canvas API. A view receives an `IContext` when it renders; the runtime turns those drawing commands into native or browser output.

This article draws text, a filled rectangle with an outline, and a circle. The preview below is an SVG generated from the same compiled view that runs in DemoApp. Start the demo, then click or touch its surface to change the rectangle's color.

## A drawing view

Derive from `View` and override `RenderCore(IContext context)`. Xui calls this method during rendering, after layout has assigned the view's `Frame`. Do not keep the context in a field: it belongs to the current render operation.

`Frame` gives the view's position and size in its parent's coordinate space. This example translates to `Frame.X` and `Frame.Y` so its drawing starts at `(0, 0)`. It then uses `Frame.Width` and `Frame.Height` to position the shapes relative to the available space.

Coordinates are logical units, not physical display pixels. Use `NFloat` (or its `nfloat` alias) for geometry; let the runtime handle display scaling.

## Try it

The example runs in a 400 by 600 viewport, which fits a small app page. At narrower widths the preview fits the article and the live view lays itself out in the available space. The code scrolls independently beside the preview on wide screens.

<div class="docs-demo-layout">

```csharp
using Xui.Core.Canvas;
using Xui.Core.Math2D;
using Xui.Core.UI;
using Xui.Core.UI.Input;
using NFloat = System.Runtime.InteropServices.NFloat;

public sealed class Example1 : View
{
    private bool alternate;
    protected override void RenderCore(IContext context)
    {
        context.Save();
        try
        {
            // Frame is in the parent's coordinate space. Draw from our own origin.
            context.Translate((Frame.X, Frame.Y));
            NFloat width = Frame.Width;
            NFloat height = Frame.Height;
            context.SetFill(new Color(0xFAF7FFFF));
            context.FillRect(new Rect(0, 0, width, height));
            context.SetFill(new Color(0x292535FF));
            context.SetFont(new Font(24, "Inter"));
            context.TextAlign = TextAlign.Center;
            context.TextBaseline = TextBaseline.Middle;
            context.FillText("Hello, Canvas!", (width / 2, height / 6));
            // Fill a rectangle, then outline it with a different paint.
            context.SetFill(new Color(alternate ? 0xD957A8FFu : 0x8538CEFFu));
            var rectangle = new Rect(width / 5, height / 3, width * 3 / 5, height / 5);
            context.FillRect(rectangle);
            context.SetStroke(new Color(0x492571FF));
            context.LineWidth = 3;
            context.StrokeRect(rectangle);
            // A circle is a path. BeginPath keeps it separate from earlier paths.
            context.BeginPath();
            context.Arc((width / 2, height * 2 / 3), 38, 0, NFloat.Pi * 2);
            context.SetFill(new Color(0xD9B6F4FF));
            context.Fill();
            context.SetFill(new Color(0x655572FF));
            context.SetFont(new Font(14, "Inter"));
            context.FillText("Click or touch to change the color", (width / 2, height * 5 / 6));
        }
        finally
        {
            context.Restore();
        }
    }

    public override void OnPointerEvent(ref PointerEventRef e, EventPhase phase)
    {
        // A small interaction to distinguish the live view from its SVG preview.
        if (phase == EventPhase.Bubble && e.Type == PointerEventType.Down)
        {
            alternate = !alternate;
            InvalidateRender();
        }
    }
}
```

<figure class="docs-demo" data-demo-url="../../../wasm/?embed=1&amp;demo=canvas/fundamentals/example1">
<div class="docs-demo-stage">
<img src="canvas-fundamentals-example1.svg" width="400" height="600" alt="Canvas fundamentals: initial rendered view" />
<button type="button" class="docs-demo-start" hidden><span class="docs-demo-pill">Start demo</span></button>
</div>
<div class="docs-demo-actions">
<button type="button" class="docs-demo-close" hidden>Close demo</button>
<span class="docs-demo-status" role="status" aria-live="polite"></span>
</div>
<figcaption>Canvas fundamentals · <a href="canvas-fundamentals-example1.cs">C# source</a> · <a href="canvas-fundamentals-example1.svg">SVG</a> · <a href="../../../wasm/?embed=1&amp;demo=canvas/fundamentals/example1">Open demo</a></figcaption>
</figure>

</div>


## Drawing state

`Save()` preserves drawing state, including paint, transforms, line width, and text settings. `Restore()` returns to that state. Pair them so your drawing does not affect the views rendered after it; `try`/`finally` keeps the pairing intact if drawing fails.

`SetFill` chooses the paint used by `FillRect`, `FillText`, and `Fill`. `SetStroke` chooses the paint for outlines, while `LineWidth` controls their thickness. `Color` accepts a packed `0xRRGGBBAA` value: the final `FF` means fully opaque.

The rectangle is filled first and outlined second. Later drawing appears over earlier drawing.

## Paths and text

`FillRect` and `StrokeRect` draw immediately. A circle uses a path instead: call `BeginPath`, add a full-turn `Arc`, and then `Fill` it. Begin a fresh path for each independent shape; saving and restoring drawing state is not a substitute for clearing the current path.

For text, set a font, horizontal alignment, and baseline before calling `FillText`. This example uses the bundled Inter font. A centered alignment and middle baseline place each label around the supplied point. The SVG preview embeds the font so it remains readable independently of the website's styles.

## Redraw when state changes

The last method handles a pointer-down event during the bubbling phase. Mouse and touch both reach this shared view input contract. The handler changes a field and calls `InvalidateRender()` to request drawing with the new color.

This intentionally small example responds immediately to a press. A production button should also handle gesture cancellation, scrolling, keyboard activation, and focus; use a ToolKit button when that is the behavior you need.

There is no animation loop here. When nothing changes, the view does not request another frame.

To test locally, clone and run:

```sh
git clone https://github.com/xuiapps/sdk.git
cd sdk
dotnet run --project Xui/Apps/DemoApp/DemoApp.Desktop.csproj -- --demo canvas/fundamentals/example1
```

Continue with the planned [Canvas and 2D drawing articles](../../reference/index.md#canvas-and-2d-drawing), or explore the [Canvas API reference](../../../api/xui-core/xui-core-canvas/index.md).
