Use canvas in javascript

Using Canvas API in JavaScript

The Canvas API provides a means for drawing graphics via JavaScript and the HTML 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 element, draws hardware-accelerated 2D and 3D graphics.

How to start using Canvas API

As a convention, the name of the id typically goes by ‘canvas’. This of course can be any name of your choosing, just pick a name that optimizes your code flow and makes sense to you.

Once you have the initial skeleton set-up, two attributes are required when setting up your canvas space. A desired ‘width’ and ‘height’ of the canvas needs to be set. Also note these attributes can be altered well into the design process if necessary.

let canvas = document.querySelector("#canvas"); const width = canvas.width; const height = canvas.height; canvas.width = 400; canvas.height = 400; 

Getting Creative

Thought these examples, I will be coding in the HTML’s body tag, nested between script tags. You’re free to code along with me in the same environment, or move your code into a separate JavaScript file.

Читайте также:  Подвал

Setting Up the Basics

Once we’ve laid out the skeleton-frame of our HTML code, it’s time to implement code that brings our creative desires to life!

 let canvas = document.querySelector("#canvas"); let context = canvas.getContext('2d'); 
  1. Place a ‘Document’ method in the Script portion of the code and pass the id of the canvas space we’ve created earlier to begin customizing our graphic. We’ll target the id by first typing the symbol of the corresponding attribute.

Quick refresher
# = id
. = class.

  1. The code below tells JavaScript the context of the drawing surface we are creating is 2D as opposed to 3D. And this can be used for creating shapes, text, and images.

let context = canvas.getContext(‘2d’);

First Shape

I’ll begin by creating a rectangle that is outlined in a 4 pixel stroke with the ‘strokeRect()’ method. The color attribute can be altered by calling the variable chained to ‘strokeStyle()’, then entering a hex color code or by the name of a color identified by JavaScript. In today’s example, I’ll use ‘green’. The parameters passed to the ‘strokeRect()’ simply refer to its top-left corner at (100, 100), and gives it a size of 400 units wide (first 400) by 400 tall (second 400).

 context.lineWidth = 4; context.strokeStyle = 'green'; context.beginPath(); context.strokeRect(100, 100, 400, 400); context.stroke(); 

Outcome

Green Outlined Rectangle

Nested Shapes

context.beginPath(); context.arc(300, 300, 100, 0, Math.PI*2); context.lineWidth = 3; context.stroke(); 

Outcome

Green Outlined Circle Inside Rectangle

Play Around With Your Code

Add in new shapes, rearrange the size of shapes, etc. just get creative and explore all that you can do with a few tweaks, or major ones! In our example, I created two side circles for the larger main circle that all together posses a Venn diagram positioning amongst each other.

context.beginPath(); context.arc(400, 300, 50, 0, Math.PI*2); context.lineWidth = 2.5; context.stroke(); context.beginPath(); context.arc(200, 300, 50, 0, Math.PI*2); context.lineWidth = 2.5; context.stroke(); 

Источник

Canvas tutorial

is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.

First introduced in WebKit by Apple for the macOS Dashboard, has since been implemented in browsers. Today, all major browsers support it.

Before you start

Using the element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The element is not supported in some older browsers, but is supported in recent versions of all major browsers. The default size of the canvas is 300 pixels × 150 pixels (width × height). But custom sizes can be defined using the HTML height and width property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

In this tutorial

  1. Basic usage
  2. Drawing shapes
  3. Applying styles and colors
  4. Drawing text
  5. Using images
  6. Transformations
  7. Compositing and clipping
  8. Basic animations
  9. Advanced animations
  10. Pixel manipulation
  11. Optimizing the canvas
  12. Finale

See also

A note to contributors

Due to an unfortunate technical error that occurred the week of June 17, 2013, we lost the history of this tutorial, including attributions to all past contributors to its content. We apologize for this, and hope you’ll forgive this unfortunate mishap.

Found a content problem with this page?

This page was last modified on Feb 19, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Basic usage of canvas

Let’s start this tutorial by looking at the HTML element itself. At the end of this page, you will know how to set up a canvas 2D context and have drawn a first example in your browser.

The element

canvas id="tutorial" width="150" height="150">canvas> 

At first sight a looks like the element, with the only clear difference being that it doesn’t have the src and alt attributes. Indeed, the element has only two attributes, width and height . These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size: if the CSS sizing doesn’t respect the ratio of the initial canvas, it will appear distorted.

Note: If your renderings seem distorted, try specifying your width and height attributes explicitly in the attributes, and not using CSS.

The id attribute isn’t specific to the element but is one of the global HTML attributes which can be applied to any HTML element (like class for instance). It is always a good idea to supply an id because this makes it much easier to identify it in a script.

The element can be styled just like any normal image ( margin , border , background …). These rules, however, don’t affect the actual drawing on the canvas. We’ll see how this is done in a dedicated chapter of this tutorial. When no styling rules are applied to the canvas it will initially be fully transparent.

Accessible content

Providing fallback content is very straightforward: just insert the alternate content inside the element to be accessed by screen readers, spiders, and other automated bots. Browsers, by default, will ignore the content inside the container, rendering the canvas normally unless isn’t supported.

For example, we could provide a text description of the canvas content or provide a static image of the dynamically rendered content. This can look something like this:

canvas id="stockGraph" width="150" height="150"> current stock price: $3.15 + 0.15 canvas> canvas id="clock" width="150" height="150"> img src="images/clock.png" width="150" height="150" alt="A clock" /> canvas> 

Telling the user to use a different browser that supports canvas does not help users who can’t read the canvas at all. Providing useful fallback text or sub DOM adds accessibility to an otherwise non-accessible element.

Required tag

If fallback content is not needed, a simple is fully compatible with all browsers that support canvas at all. This should only be used if the canvas is purely presentational.

The rendering context

The canvas is initially blank. To display something, a script first needs to access the rendering context and draw on it. The element has a method called getContext() , used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context. For 2D graphics, such as those covered by this tutorial, you specify «2d» to get a CanvasRenderingContext2D .

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

The first line in the script retrieves the node in the DOM representing the element by calling the document.getElementById() method. Once you have the element node, you can access the drawing context using its getContext() method.

Checking for support

const canvas = document.getElementById("tutorial"); if (canvas.getContext)  const ctx = canvas.getContext("2d"); // drawing code here > else  // canvas-unsupported code here > 

A skeleton template

Here is a minimalistic template, which we’ll be using as a starting point for later examples.

Note: it is not good practice to embed a script inside HTML. We do it here to keep the example concise.

doctype html> html lang="en-US"> head> meta charset="utf-8" /> title>Canvas tutorialtitle> style> canvas  border: 1px solid black; > style> head> body> canvas id="tutorial" width="150" height="150">canvas> script> function draw()  const canvas = document.getElementById("tutorial"); if (canvas.getContext)  const ctx = canvas.getContext("2d"); > > draw(); script> body> html> 

The script includes a function called draw() , which is executed once the page finishes loading; this is done by listening for the load event on the document. This function, or one like it, could also be called using setTimeout() , setInterval() , or any other event handler, as long as the page has been loaded first.

Here is how a template would look in action. As shown here, it is initially blank.

A simple example

To begin, let’s take a look at a simple example that draws two intersecting rectangles, one of which has alpha transparency. We’ll explore how this works in more detail in later examples.

doctype html> html lang="en-US"> head> meta charset="UTF-8" /> title>Canvas experimenttitle> head> body> canvas id="canvas" width="150" height="150">canvas> script type="application/javascript"> function draw()  const canvas = document.getElementById("canvas"); if (canvas.getContext)  const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200, 0, 0)"; ctx.fillRect(10, 10, 50, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; ctx.fillRect(30, 30, 50, 50); > > draw(); script> body> html> 

This example looks like this:

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью