Skip to main content

Canvas API

The Canvas API provides a means for drawing graphics via JavaScript and the HTML <canvas> element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

The Canvas API largely focuses on 2D graphics. The WebGL API, which also uses the <canvas> element, draws hardware-accelerated 2D and 3D graphics.

Basic example

This simple example draws a green rectangle onto a canvas.

HTML

<canvas id="canvas"></canvas>

JavaScript

The Document.getElementById() method gets a reference to the HTML <canvas> element. Next, the HTMLCanvasElement.getContext() method gets that element's context—the thing onto which the drawing will be rendered.

The actual drawing is done using the CanvasRenderingContext2D interface. The fillStyle property makes the rectangle green. The fillRect() method places its top-left corner at (10, 10), and gives it a size of 150 units wide by 100 tall.

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 150, 100);

Result

Comments

Popular posts from this blog

Using textures in WebGL

Loading textures The first thing to do is add code to load the textures. In our case, we'll be using a single texture, mapped onto all six sides of our rotating cube, but the same technique can be used for any number of textures. Note: It's important to note that the loading of textures follows cross-domain rules; that is, you can only load textures from sites for which your content has CORS approval. See Cross-domain textures below for details. The code that loads the texture looks like this: // // Initialize a texture and load an image. // When the image finished loading copy it into the texture. // function loadTexture(gl, url) {   const texture = gl.createTexture();   gl.bindTexture(gl.TEXTURE_2D, texture);   // Because images have to be download over the internet   // they might take a moment until they are ready.   // Until then put a single pixel in the texture so we can   // use it immediately. When the image has finished downloading   // we'l...

Upload video 2

Upload image 4