Skip to content
Skip to content
sujatad.net

Blogging about technology and leadership

← 5 tools I like
WCF Data Services and Enums →
-->

Using canvas element in HTML 5

Posted on October 10, 2010 by sujatad

Canvas is an interesting HTML5 feature. HTML 5 defines the <canvas> element as “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.” A canvas is a rectangle in your page where you can use JavaScript to draw anything you want.

Here’s a quick example on how to use this feature – create the element first and then add javascript code to manipulate the element – in this case to draw a triangle.

<html>
<head>
<title>Canvas</title>
<script type="text/javascript">
// When the window has loaded, DOM is ready. Run the DrawInCanvas() function.
window.onload = DrawInCanvas;

function DrawInCanvas()
{
// Get a reference to the element.
var el = document.getElementById(‘idCanvas’);

//verify if this feature exists on browser
if (el && el.getContext)
{
//initialize context
var drawingContext = el.getContext(‘2d’);
if (drawingContext)
{
// Set the style properties – red color
drawingContext.fillStyle = ‘#eee’;
drawingContext.strokeStyle = ‘#f00’;
drawingContext.lineWidth = 3;

//Start drawing
drawingContext.beginPath();
drawingContext.moveTo(10, 10);
drawingContext.lineTo(100, 10);
drawingContext.lineTo(10, 100);
drawingContext.lineTo(10, 10);

//fill the shape
drawingContext.fill();

//display
drawingContext.stroke();
drawingContext.closePath();
}
}
}

</script>

<style type="text/css">
canvas { border: 1px solid black; }</style>
</head>
<body>
<canvas id="idCanvas" width="200" height="200"></canvas>
</body>
</html>

About sujatad

Technical Blogger
View all posts by sujatad
This entry was posted in .NET, HTML5, Web. Bookmark the <a href="https://sujatad.net/net/using-canvas-element-in-html-5/" title="Permalink to Using canvas element in HTML 5" rel="bookmark">permalink</a>.
← 5 tools I like
WCF Data Services and Enums →

Comments are closed.

© 2025 | Blog info WordPress Theme | By Bharat Kambariya