Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

CHAPTER 9: Canvas > Canvas Basics

Canvas Basics

First in Chapter 2 I created a simple canvas element and drew a rectangle and as long as your DOCTYPE was HTML5 you were able to paste this code into any HTML page and your browser would show you a red square.

<canvas id="simplecanvas"></canvas>
<script type="text/javascript">
var canvas = document.querySelector('#simplecanvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle='rgb(255,0,0)';
ctx.fillRect(0,0,100,100);
</script>

You can see from this example you need two basic objects, the canvas and the context.

Canvas Object

This object is a standard HTML element. You can reference it via document.getElementById or document.querySelector(ELEMENT_ID). This object has two properties outside the global attributes called height and width. It has three methods:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial