Edit HTML5 Canvas – С# Examples

What is HTML Canvas?

The HTML Canvas element is an HTML5 element in an HTML document that is added using the <canvas> tag. The <canvas> element is a container for graphics, and you must use JavaScript to actually draw the graphics – dynamically create and manipulate graphics. HTML5 Canvas provides a 2D drawing context that can be used to create and edit graphic elements such as lines, paths, shapes, images, and text. The <canvas> element is part of HTML5 and provides scriptable dynamic rendering of 2D shapes and bitmaps. This is a low-level procedural model that updates a bitmap. HTML5 Canvas, which is used for rendering graphs, game graphics, art, or other visual images on the fly, is in the list of built-in formats of the Aspose.HTML class library.

The <canvas> element must have:

The HTML Canvas element also has other attributes that you can set to configure its behavior and appearance. For example, if you want to to add a border, use a style attribute. The <canvas> element also supports the Global Attributes and in HTML.

HTML5 Canvas – How to Edit in C#

To render canvas as a part of an HTML document, you do not need any particular manipulation, just render the document as you usually do. The following code snippet demonstrates how to work with a document that contains an HTML5 Canvas element:

 1// For complete examples and data files, please go to https://github.com/aspose-html/Aspose.HTML-for-.NET
 2// Prepare a document with HTML5 Canvas inside and save it to the file 'document.html'
 3var code = @"
 4    <canvas id=myCanvas width='200' height='100' style='border:1px solid #d3d3d3;'></canvas>
 5    <script>
 6        var c = document.getElementById('myCanvas');
 7        var context = c.getContext('2d');
 8        context.font = '20px Arial';
 9        context.fillStyle = 'red';
10        context.fillText('Hello World', 40, 50);
11    </script>";
12System.IO.File.WriteAllText("document.html", code);
14// Initialize an HTML document from the html file
15using (var document = new HTMLDocument("document.html"))
17    // Convert HTML to PDF
18    Aspose.Html.Converters.Converter.ConvertHTML(document, new Aspose.Html.Saving.PdfSaveOptions(), "output.pdf");

In the example, we create an HTML document from scratch. The code variable contains HTML content that generates a document with an embedded <canvas> element, and uses JavaScript to draw “Hello World” on the canvas. Let’s break down the C# code step by step:

  1. Prepare an HTML code with HTML5 Canvas inside and use the System.IO.File.WriteAllText() method to write the HTML code to a file named “document.html”.
  2. Initialize an HTML document from the file using the HTMLDocument class.
  3. Call the ConvertHTML(document, options, outputPath) method to convert HTML to PDF with the default save options.

Canvas Rendering Context 2D

Besides processing HTML5 Canvas as a part of an HTML document, you can work with canvas directly inside your C# code. Aspose.HTML for .NET provides ICanvasRenderingContext2D interface for these operations, which is fully based on the official standard and used for drawing 2D graphics on a canvas element in HTML. It provides a set of methods and properties that allow developers to create and manipulate graphics, such as lines, shapes, text, and images, within the canvas.

Key Features of CanvasRenderingContext2D

The <canvas> element, combined with the 2D rendering context, allows developers to create dynamic and interactive visuals directly within a web page. Here are some key aspects of CanvasRenderingContext2D:

  1. With methods like FillRect() and StrokeRect() you can effortlessly draw shapes.
  2. CanvasRenderingContext2D facilitates text rendering on the canvas using methods such as FillText() and StrokeText(), allowing for dynamic text display with varying styles and fonts.
  3. You can customize the appearance of drawn elements by setting properties like FillStyle and StrokeStyle, enabling the use of gradients, patterns, and solid colors.
  4. You can apply transformations like translation, rotation, and scaling, which can dynamically manipulate the canvas space, facilitating complex graphic arrangements.
  5. CanvasRenderingContext2D supports drawing and manipulating images on the canvas through methods like DrawImage(), enhancing the potential for incorporating graphics into the user interface.

Render HTML5 Canvas 2D to PDF

Following code snippet shows how to use the drawing feature of HTML5 Canvas to render a custom text filled in with the gradient brush.

 1// For complete examples and data files, please go to https://github.com/aspose-html/Aspose.HTML-for-.NET
 2// Create an empty HTML document
 3using (var document = new Aspose.Html.HTMLDocument())
 5    // Create the Canvas element
 6    var canvas = (Aspose.Html.HTMLCanvasElement)document.CreateElement("canvas");
 8    // with a specified size
 9    canvas.Width = 300;
10    canvas.Height = 150;
12    // and append it to the document body
13    document.Body.AppendChild(canvas);
15    // Get the canvas rendering context to draw
16    var context = (Aspose.Html.Dom.Canvas.ICanvasRenderingContext2D)canvas.GetContext("2d");
18    // Prepare the gradient brush
19    var gradient = context.CreateLinearGradient(0, 0, canvas.Width, 0);
20    gradient.AddColorStop(0, "magenta");
21    gradient.AddColorStop(0.5, "blue");
22    gradient.AddColorStop(1.0, "red");
24    // Assign brush to the content
25    context.FillStyle = gradient;
26    context.StrokeStyle = gradient;
28    // Write the Text
29    context.FillText("Hello World!", 10, 90, 500);
31    // Fill the Rectangle
32    context.FillRect(0, 95, 300, 20);
34    // Create the PDF output device
35    using (var device = new Aspose.Html.Rendering.Pdf.PdfDevice("canvas.pdf"))
36    {
37        // Render HTML5 Canvas to PDF
38        document.RenderTo(device);
39    }

In the example we looked at above, an HTML document was rendered in PDF format using the RenderTo(device) method. But you can choose a different rendering device and convert the HTML document to another format that you need. Rendering canvas content to other formats, such as images or PDFs, can help ensure consistent and reliable display across different browsers, make it easier for users to print or share visually consistent documents, and can be valuable for archiving purposes. For some applications, rendering canvas content to a static format can improve security by preventing end users from manipulating or tampering with dynamic visuals.

Thus, rendering HTML5 canvas content to other formats provides flexibility, improves compatibility, and opens up various possibilities for sharing, archiving, and integrating dynamic graphics in different contexts. The choice of format depends on the specific needs and goals of the web application.

To learn more about rendering process, please read the Rendering Device article.

Rendering options give you additional control over the rendering process. To learn more about them, please read the Rendering Options article.

To learn more about how to use HTML5 Canvas, you can read the popular public HTML Canvas Tutorial.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.