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:
id
attribute so it can be referred to by JavaScript.width
andheight
attributes to define the size of the canvas.
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// Prepare an output path
2string outputPath = Path.Combine(OutputDir, "output.pdf");
3
4// Prepare a document with HTML5 Canvas inside and save it to the file "document.html"
5var code = @"
6 <canvas id=myCanvas width='200' height='100' style='border:1px solid #d3d3d3;'></canvas>
7 <script>
8 var c = document.getElementById('myCanvas');
9 var context = c.getContext('2d');
10 context.font = '30px Arial';
11 context.fillStyle = 'red';
12 context.fillText('Hello, World', 40, 50);
13 </script>";
14
15System.IO.File.WriteAllText("document.html", code);
16
17// Initialize an HTML document from the html file
18using (var document = new HTMLDocument("document.html"))
19{
20 // Convert HTML to PDF
21 Converter.ConvertHTML(document, new PdfSaveOptions(), outputPath);
22}
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:
- 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”. - Initialize an HTML document from the file using the HTMLDocument class.
- 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:
- With methods like FillRect() and StrokeRect() you can effortlessly draw shapes.
- CanvasRenderingContext2D facilitates text rendering on the canvas using methods such as FillText() and StrokeText(), allowing for dynamic text display with varying styles and fonts.
- You can customize the appearance of drawn elements by setting properties like FillStyle and StrokeStyle, enabling the use of gradients, patterns, and solid colors.
- You can apply transformations like translation, rotation, and scaling, which can dynamically manipulate the canvas space, facilitating complex graphic arrangements.
- 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 // Create an empty HTML document
2 using var document = new HTMLDocument();
3
4 // Create a <canvas> element
5 var canvas = (HTMLCanvasElement)document.CreateElement("canvas");
6
7 // with a specified size
8 canvas.Width = 500;
9 canvas.Height = 150;
10
11 // and append it to the document body
12 document.Body.AppendChild(canvas);
13
14 // Get the canvas rendering context to draw
15 var context = (Html.Dom.Canvas.ICanvasRenderingContext2D)canvas.GetContext("2d");
16
17 // Prepare a gradient brush
18 var gradient = context.CreateLinearGradient(0, 0, canvas.Width, 0);
19 gradient.AddColorStop(0, "magenta");
20 gradient.AddColorStop(0.4, "blue");
21 gradient.AddColorStop(0.9, "red");
22
23 // Assign the brush to the content
24 context.FillStyle = gradient;
25 context.StrokeStyle = gradient;
26
27 // Write the text
28 context.FillText("Hello, World!", 10, 90, 500);
29
30 // Fill the rectangle
31 context.FillRect(0, 95, 500, 100);
32
33 // Prepare an output path
34 string outputPath = Path.Combine(OutputDir, "canvas.pdf");
35
36 // Create the PDF output device
37 using (var device = new PdfDevice(outputPath))
38 {
39 // Render HTML5 Canvas to PDF
40 document.RenderTo(device);
41 }
42}
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.