Search completed in 1.34 seconds.
491 results for "canvas":
Your results are loading. Please wait...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
Web › HTML › Element › canvas
Content categories Flow content, phrasing content, embedded content, palpable content. Permitted content Transparent but with no interactive content descendants except for <a> elements, <button> elements, <input> elements whose type attribute is checkbox, radio, or button. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content. Implicit ARIA role No corresponding role Permitted ARIA roles Any DOM interface HTMLCanvasElement Attributes This element's attributes include the global attributes. ...
...nt descendants except for <a> elements, <button> elements, <input> elements whose type attribute is checkbox, radio, or button. Tag omission None, both the starting and ending tag are mandatory. Permitted parents Any element that accepts phrasing content. Implicit ARIA role No corresponding role Permitted ARIA roles Any DOM interface HTMLCanvasElement Attributes This element's attributes include the global attributes. height The height of the coordinate space in CSS pixels. Defaults to 150. moz-opaque Lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported by Mozilla-based browsers; use the standardized...
...lement Attributes This element's attributes include the global attributes. height The height of the coordinate space in CSS pixels. Defaults to 150. moz-opaque Lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This is only supported by Mozilla-based browsers; use the standardized canvas.getContext('2d', { alpha: false }) instead. width The width of the coordinate space in CSS pixels. Defaults to 300. Usage notes Alternative content You may (and should) provide alternate content inside the <canvas> block. That content will be rendered both on older browsers that don't support canvas and in browsers with JavaScript disabled. Providing a useful fallback text or sub DOM helps ...
...And 16 more matches
CanvasCaptureMediaStreamTrack.canvas - Web APIs
The CanvasCaptureMediaStreamTrack canvas read-only property returns the HTMLCanvasElement from which frames are being captured. Syntax var elt = stream.canvas; Value An HTMLCanvasElement indicating the canvas which is the source of the frames being captured. Example // Find the canvas element to capture var canvasElt = document.getElementsByTagName("canvas")[0]; // Get the stream var stream = canvasElt.captureStream(25); // 25 FPS // Do things to the stream ... // Obtain the canvas associated with the stream var canvas = stream.canvas; Specifications Specification Status Comment Media Capture from DOM ElementsThe definition of 'CanvasCaptureMediaStreamTrack.canvas' in that specification. Working Draft Initial definition ...
CanvasRenderingContext2D.canvas - Web APIs
The CanvasRenderingContext2D.canvas property, part of the Canvas API, is a read-only reference to the HTMLCanvasElement object that is associated with a given context. It might be null if there is no associated <canvas> element. Syntax ctx.canvas; Examples Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a reference to the canvas element within the CanvasRenderingContext2D by using the canvas property: var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.canvas // HTMLCanvasElement Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.canvas' in that specification. Living Standard ...
Drawing shapes with canvas - Web APIs
<< PreviousNext >> Now that we have set up our canvas environment, we can get into the details of how to draw on the canvas. By the end of this article, you will have learned how to draw rectangles, triangles, lines, arcs and curves, providing familiarity with some of the basic shapes. Working with paths is essential when drawing objects onto the canvas and we will see how that can be done. The grid Before we can start drawing, we need to talk about the canvas grid or coordinate space. Our HTML skeleton from the previous page had a canvas element 150 pixels wide and 150 pixels high. To the right, you see this canvas with the default grid overlayed. Normally 1 unit in the grid corresponds to 1 pixel on the canvas. The origin of this grid is positioned in the top left corner a...
...rdinate (0,0). All elements are placed relative to this origin. So the position of the top left corner of the blue square becomes x pixels from the left and y pixels from the top, at coordinate (x,y). Later in this tutorial we'll see how we can translate the origin to a different position, rotate the grid and even scale it, but for now we'll stick to the default. ...
...wing rectangles Unlike SVG, <canvas> only supports two primitive shapes: rectangles and paths (lists of points connected by lines). All other shapes must be created by combining one or more paths. Luckily, we have an assortment of path drawing functions which make it possible to compose very complex shapes. First let's look at the rectangle. There are three functions that draw rectangles on the canvas: fillRect(x, y, width, height) Draws a filled rectangle. strokeRect(x, y, width, height) Draws a rectangular outline. clearRect(x, y, width, height) Clears the specified rectangular area, making it fully transparent. Each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width ...
...And 63 more matches
CanvasRenderingContext2D - Web APIs
The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and other objects. See the interface's properties and methods in the sidebar and below. The Canvas tutorial has more explanation, examples, and resources, as well. Basic example To get a CanvasRenderingContext2D instance, you must first have an HTML <canvas> element to work with: <canvas id="my-house" width="300" height="300"></canvas> To get the canvas' 2D rendering context, call getContext() on the <canvas> element, supplying '2d' as the argument: const canvas = document.getElementById('my-house'); const ctx = canvas.getContext('2d'); With the context in hand, you can draw anything you like. This c...
... draws a house: // Set line width ctx.lineWidth = 10; // Wall ctx.strokeRect(75, 140, 150, 110); // Door ctx.fillRect(130, 190, 40, 60); // Roof ctx.beginPath(); ctx.moveTo(50, 140); ctx.lineTo(150, 60); ctx.lineTo(250, 140); ctx.closePath(); ctx.stroke(); The resulting drawing looks like this: Reference Drawing rectangles There are three methods that immediately draw rectangles to the canvas. CanvasRenderingContext2D.clearRect() Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content. CanvasRenderingContext2D.fillRect() Draws a filled rectangle at (x, y) position whose size is determined by width and height. CanvasRenderingContext2D.strokeRect() Paints a rectangle which has a startin...
... the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content. CanvasRenderingContext2D.fillRect() Draws a filled rectangle at (x, y) position whose size is determined by width and height. CanvasRenderingContext2D.strokeRect() Paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style. Drawing text The following methods draw text. See also the TextMetrics object for text properties. CanvasRenderingContext2D.fillText() Draws (fills) a given text at the given (x, y) position. CanvasRenderingContext2D.strokeText() Draws (strokes) a given text at the given (x, y) position. CanvasRenderingContext2D.measureText() Returns a TextMetrics objec...
...And 41 more matches
Canvas code snippets - Archive of obsolete content
For general information about using <canvas> see the canvas topic page. Code usable from Web content Getting the number of pixels of a certain color in a canvas The following function will return the number of pixels in a canvas that have the RGB color of r, g and b. This can be very useful to compare for example if a user has painted over another area as explained in this blog post. ...
...ormation about using <canvas> see the canvas topic page. Code usable from Web content Getting the number of pixels of a certain color in a canvas The following function will return the number of pixels in a canvas that have the RGB color of r, g and b. This can be very useful to compare for example if a user has painted over another area as explained in this blog post. ...
...see the canvas topic page. Code usable from Web content Getting the number of pixels of a certain color in a canvas The following function will return the number of pixels in a canvas that have the RGB color of r, g and b. This can be very useful to compare for example if a user has painted over another area as explained in this blog post. ...
...And 33 more matches
Pixel manipulation with canvas - Web APIs
It contains the following read-only attributes: width The width of the image in pixels. height The height of the image in pixels. ...
...It contains the following read-only attributes: width The width of the image in pixels. height The height of the image in pixels. ...
...It contains the following read-only attributes: width The width of the image in pixels. height The height of the image in pixels. data A Uint8ClampedArray representing a one-dimensional array containing the data in the RGBA order, with integer values between 0 and 255 (included). ...
...And 32 more matches
Basic usage of canvas - Web APIs
<< PreviousNext >> Let's start this tutorial by looking at the <canvas> 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 <canvas> element <canvas id="tutorial" width="150" height="150"></canvas> At first sight a <canvas> looks like the <img> element, with the only clear difference being that it doesn't have the src and alt attributes. Indeed, the <canvas> 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 i...
...ment 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 <canvas> attributes, and not using CSS. The id attribute isn't specific to the <canvas> 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 ma...
...s seem distorted, try specifying your width and height attributes explicitly in the <canvas> attributes, and not using CSS. The id attribute isn't specific to the <canvas> 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 <canvas> 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. ...
...And 21 more matches
CanvasRenderingContext2D.arcTo() - Web APIs
The arc is automatically connected to the path's latest point with a straight line, if necessary for the specified parameters. This method is commonly used for making rounded corners. Note: Be aware that you may get unexpected results when using a relatively large radius: the arc's connecting line will go in whatever direction it must to meet the specified radius. Syntax void ctx.arcTo(x1, y1, x2, y2, radius); Parameters x1 The x-axis coordinate of the first control point. y1 The y-axis coordinate of the first control point. x2 The x-axis coordinate of the second control point. ...
... Examples How arcTo works One way to think about arcTo() is to imagine two straight segments: one from the starting point to a first control point, and another from there to a second control point. Without arcTo(), these two segments would form a sharp corner: arcTo() creates a circular arc that fits this corner and smooths is out. In other words, the arc is tangential to both segments. ...
...How arcTo works One way to think about arcTo() is to imagine two straight segments: one from the starting point to a first control point, and another from there to a second control point. Without arcTo(), these two segments would form a sharp corner: arcTo() creates a circular arc that fits this corner and smooths is out. In other words, the arc is tangential to both segments. ...
...And 20 more matches
CanvasRenderingContext2D.createPattern() - Web APIs
The CanvasRenderingContext2D.createPattern() method of the Canvas 2D API creates a pattern using the specified image and repetition. This method returns a CanvasPattern. This method doesn't draw anything to the canvas directly. The pattern it creates must be assigned to the CanvasRenderingContext2D.fillStyle or CanvasRenderingContext2D.strokeStyle properties, after which it is applied to any subsequent drawing. Syntax CanvasPattern ctx.createPattern(image, repetition); Parameters image A CanvasImageSource to be used as the pattern's image. ...
...Possible values are: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither direction) If repetition is specified as an empty string ("") or null (but not undefined), a value of "repeat" will be used. ...
...ontext2D.strokeStyle properties, after which it is applied to any subsequent drawing. Syntax CanvasPattern ctx.createPattern(image, repetition); Parameters image A CanvasImageSource to be used as the pattern's image. It can be any of the following: HTMLImageElement (<img>) SVGImageElement (<image>) HTMLVideoElement (<video>, by using the capture of the video) HTMLCanvasElement (<canvas>) ImageBitmap OffscreenCanvas repetition A DOMString indicating how to repeat the pattern's image. Possible values are: "repeat" (both directions) "repeat-x" (horizontal only) "repeat-y" (vertical only) "no-repeat" (neither direction) If repetition is specified as an empty string ("") or null (but not undefined), a value of "repeat" will be used. Return value CanvasPat...
...And 17 more matches
CanvasRenderingContext2D.drawImage() - Web APIs
sx Optional The x-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. ...
... The CanvasRenderingContext2D.drawImage() method of the Canvas 2D API provides different ways to draw an image onto the canvas. Syntax void ctx.drawImage(image, dx, dy); void ctx.drawImage(image, dx, dy, dWidth, dHeight); void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); Parameters image An element to draw into the context. The specification permits any canvas image source (CanvasImageSource), specifically, a CSSImageValue, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement, an HTMLCanvasElement, an ImageBitmap, or an OffscreenCanvas. sx Optional The x-axis coordinate of the top left corner of the sub-rectangle of the source image to draw into the destination context. sy Optional The y-axis coordinate of the top left corner of the sub-rectangle ...
...text. sWidth Optional The width of the sub-rectangle of the source image to draw into the destination context. If not specified, the entire rectangle from the coordinates specified by sx and sy to the bottom-right corner of the image is used. sHeight Optional The height of the sub-rectangle of the source image to draw into the destination context. dx The x-axis coordinate in the destination canvas at which to place the top-left corner of the source image. dy The y-axis coordinate in the destination canvas at which to place the top-left corner of the source image. dWidth Optional The width to draw the image in the destination canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in width when drawn. dHeight Optional The height to draw the image in t...
...And 15 more matches
Building up a basic demo with the PlayCanvas engine - Game development
Built for modern browsers, PlayCanvas is a fully-featured 3D game engine with resource loading, an entity and component system, advanced graphics manipulation, collision and physics engine (built with ammo.js), audio, and facilities to handle control inputs from various devices (including gamepads). That's quite an impressive list of features -- let's see some in action. We will try putting together a simple demo first -- a cube rendered on the screen. If you have already worked through our Building up a basic demo with Three.js article (or you are familiar with other 3D libraries) you'll notice that PlayCanvas works on similar concepts: camera, light and objects. Environment setup To start developing with PlayCanvas, you don't need much. You should start off by: Making sure you...
...ther 3D libraries) you'll notice that PlayCanvas works on similar concepts: camera, light and objects. Environment setup To start developing with PlayCanvas, you don't need much. You should start off by: Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Creating a directory to store your experiments in. Saving a copy of the latest PlayCanvas engine inside your directory. Opening the PlayCanvas documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use. ...
...ebGL support, such as the latest Firefox or Chrome. Creating a directory to store your experiments in. Saving a copy of the latest PlayCanvas engine inside your directory. Opening the PlayCanvas documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use. ...
...And 14 more matches
CanvasRenderingContext2D.clip() - Web APIs
It replaces any previous clipping region. In the image below, the red outline represents a clipping region shaped like a star. Only those parts of the checkerboard pattern that are within the clipping region get drawn. Note: Be aware that the clipping region is only constructed from shapes added to the path. It doesn't work with shape primitives drawn directly to the canvas, such as fillRect(). Instead, you'd have to use rect() to add a rectangular shape to the path before calling clip(). ...
...current clipping region. It replaces any previous clipping region. In the image below, the red outline represents a clipping region shaped like a star. Only those parts of the checkerboard pattern that are within the clipping region get drawn. Note: Be aware that the clipping region is only constructed from shapes added to the path. It doesn't work with shape primitives drawn directly to the canvas, such as fillRect(). Instead, you'd have to use rect() to add a rectangular shape to the path before calling clip(). Syntax void ctx.clip([fillRule]); void ctx.clip(path [, fillRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the clipping region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-o...
...alues: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to use as the clipping region. Examples A simple clipping region This example uses the clip() method to create a clipping region according to the shape of a circular arc. Two rectangles are then drawn; only those parts within the clipping region are rendered. ...
...And 14 more matches
Optimizing canvas - Web APIs
<< PreviousNext >> The <canvas> element is one of the most widely used tools for rendering 2D graphics on the web. However, when websites and apps push the Canvas API to its limits, performance begins to suffer. This article provides suggestions for optimizing your use of the canvas element to ensure that your graphics perform well. Performance tips The following is a collection of tips to improve canvas performance. Pre-render similar primitives or repeating objects on an offscreen canvas If you find yourself repeating some of the same drawing operations on each animation frame, consider offloading them to an offscreen canvas. ...
...sure that your graphics perform well. Performance tips The following is a collection of tips to improve canvas performance. Pre-render similar primitives or repeating objects on an offscreen canvas If you find yourself repeating some of the same drawing operations on each animation frame, consider offloading them to an offscreen canvas. You can then render the offscreen image to your primary canvas as often as needed, without unnecessarily repeating the steps needed to generate it in the first place. ...
...performance. Pre-render similar primitives or repeating objects on an offscreen canvas If you find yourself repeating some of the same drawing operations on each animation frame, consider offloading them to an offscreen canvas. You can then render the offscreen image to your primary canvas as often as needed, without unnecessarily repeating the steps needed to generate it in the first place. myCanvas.offscreenCanvas = document.createElement('canvas'); myCanvas.offscreenCanvas.width = myCanvas.width; myCanvas.offscreenCanvas.height = myCanvas.height; myCanvas.getContext('2d').drawImage(myCanvas.offScreenCanvas, 0, 0); Avoid floating-point coordinates and use integers instead Sub-pixel rendering occurs when you render objects on a canvas without whole values. ctx.drawImage(myImage, 0.3, 0.
...And 14 more matches
HTMLCanvasElement.toBlob() - Web APIs
If type is not specified, the image type is image/png. The created image is in a resolution of 96dpi. The third argument is used when creating images using lossy compression (namely, image/jpeg) to specify the quality of the output. Syntax canvas.toBlob(callback, mimeType, qualityArgument); Parameters callback A callback function with the resulting Blob object as a single argument. mimeType Optional A DOMString indicating the image format. The default type is image/png. ...
...tring indicating the image format. The default type is image/png. qualityArgument Optional A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. Other arguments are ignored. Return value None. ...
... image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default values 0.92 and 0.80 are used for image/jpeg and image/webp respectively. Other arguments are ignored. Return value None. Exceptions SecurityError The canvas's bitmap is not origin clean; at least some of its contents come from secure Examples Getting a file representing the canvas Once you have drawn content into a canvas, you can convert it into a file of any supported image format. ...
...And 14 more matches
OffscreenCanvas - Web APIs
The OffscreenCanvas interface provides a canvas that can be rendered off screen. It is available in both the window and worker contexts. Constructors OffscreenCanvas() OffscreenCanvas constructor. Creates a new OffscreenCanvas object. Properties OffscreenCanvas.height The height of the offscreen canvas. OffscreenCanvas.width The width of the offscreen canvas. Methods OffscreenCanvas.getContext() Returns a rendering context for the offscreen canvas. OffscreenCanvas.convertToBlob() Creates a Blob object representing the image contained in the canvas. OffscreenCanvas.transferToImageBitmap() Creates an ImageBitmap object from the most recently rendered image of the OffscreenCanvas. ...
...Once a new frame has finished rendering in this context, the transferToImageBitmap() method can be called to save the most recent rendered image. ...
...Once a new frame has finished rendering in this context, the transferToImageBitmap() method can be called to save the most recent rendered image. ...
...And 14 more matches
CanvasRenderingContext2D.addHitRegion() - Web APIs
They let you route events to DOM elements, and make it possible for users to explore the canvas without seeing it. Syntax void ctx.addHitRegion(options); Options The options argument is optional. When provided, it is an Object which can contain the following properties: path A Path2D object describing the area of the hit region. If not provided, the current path is used. fillRule The algorithm by which to determine if a point is inside or outside the hit region. Possible values: nonzero: The non-zero winding rule. Default rule. evenodd: The even-odd winding rule. ...
...winding rule. Default rule. evenodd: The even-odd winding rule. id The ID for this hit region to reference it for later use in events, for example. parentID The ID of the parent region for cursor fallback and navigation by accessibility tools. cursor The cursor to use when the mouse is over this region (defaults to inherit). Inherits the cursor of the parent hit region, if any, or the canvas element's cursor. control An element (descendant of the canvas) to which events are to be routed. Defaults to null. label A text label for accessibility tools to use as a description of the region, if there is no control. Defaults to null. role An ARIA role for accessibility tools to determine how to represent this region, if there is no control. Defaults to null. Examples Using the addH...
...ents are to be routed. Defaults to null. label A text label for accessibility tools to use as a description of the region, if there is no control. Defaults to null. role An ARIA role for accessibility tools to determine how to represent this region, if there is no control. Defaults to null. Examples Using the addHitRegion method This example demonstrates the addHitRegion() method. ...
...And 13 more matches
CanvasRenderingContext2D.textAlign - Web APIs
The alignment is relative to the x value of the fillText() method. For example, if textAlign is "center", then the text's left edge will be at x - (textWidth / 2). Syntax ctx.textAlign = "left" || "right" || "center" || "start" || "end"; Options Possible values: "left" The text is left-aligned. "right" The text is right-aligned. "center" The text is centered. "start" The text is aligned at the normal start of the line (left-aligned for left-to-right locales, right-aligned for right-to-left locales). "end" The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales). ...
...ed for left-to-right locales, right-aligned for right-to-left locales). "end" The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales). The default value is "start". Examples General text alignment This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right". ...
...-to-right locales, right-aligned for right-to-left locales). "end" The text is aligned at the normal end of the line (right-aligned for left-to-right locales, left-aligned for right-to-left locales). The default value is "start". Examples General text alignment This example demonstrates the three "physical" values of the textAlign property: "left", "center", and "right". ...
...And 13 more matches
CanvasRenderingContext2D.isPointInPath() - Web APIs
Syntax ctx.isPointInPath(x, y [, fillRule]); ctx.isPointInPath(path, x, y [, fillRule]); Parameters x The x-axis coordinate of the point to check, unaffected by the current transformation of the context. y The y-axis coordinate of the point to check, unaffected by the current transformation of the context. fillRule The algorithm by which to determine if a point is inside or outside the path. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to check against. If unspecified, the current path is used. ...
...e even-odd winding rule. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the specified point is contained in the current or specified path, otherwise false. Examples Checking a point in the current path This example uses the isPointInPath() method to check if a point is within the current path. ...
...winding rule. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the specified point is contained in the current or specified path, otherwise false. Examples Checking a point in the current path This example uses the isPointInPath() method to check if a point is within the current path. ...
...And 12 more matches
CanvasRenderingContext2D.isPointInStroke() - Web APIs
Syntax ctx.isPointInStroke(x, y); ctx.isPointInStroke(path, x, y); Parameters x The x-axis coordinate of the point to check. y The y-axis coordinate of the point to check. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. ...
...check. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. ...
...h A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. ...
...And 12 more matches
CanvasRenderingContext2D.lineDashOffset - Web APIs
Syntax ctx.lineDashOffset = value; value A float specifying the amount of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. ...
...roperty of the Canvas 2D API sets the line dash offset, or "phase." Note: Lines are drawn by calling the stroke() method. Syntax ctx.lineDashOffset = value; value A float specifying the amount of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. ...
...the Canvas 2D API sets the line dash offset, or "phase." Note: Lines are drawn by calling the stroke() method. Syntax ctx.lineDashOffset = value; value A float specifying the amount of the line dash offset. The default value is 0.0. Examples Offsetting a line dash This example draws two dashed lines. The first has no dash offset. The second has a dash offset of 4. ...
...And 12 more matches
HTMLCanvasElement.toDataURL() - Web APIs
The returned image is in a resolution of 96 dpi. If the height or width of the canvas is 0 or larger than the maximum canvas size, the string "data:," is returned. If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported. Chrome also supports the image/webp type. Syntax canvas.toDataURL(type, encoderOptions); Parameters type Optional A DOMString indicating the image format. The default format type is image/png. ...
...The default format type is image/png. ...
...encoderOptions Optional A Number between 0 and 1 indicating the image quality to use for image formats that use lossy compression such as image/jpeg and image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored. Return value A DOMString containing the requested data URI. ...
...And 12 more matches
CanvasRenderingContext2D.rotate() - Web APIs
Syntax void ctx.rotate(angle); Parameters angle The rotation angle, clockwise in radians. You can use degree * Math.PI / 180 to calculate a radian from a degree. The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate() method. Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
... The rotation angle, clockwise in radians. You can use degree * Math.PI / 180 to calculate a radian from a degree. The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate() method. Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
...gree * Math.PI / 180 to calculate a radian from a degree. The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate() method. Examples Rotating a shape This example rotates a rectangle by 45?. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape. ...
...And 11 more matches
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
It is similar to Element.scrollIntoView(). Syntax void ctx.scrollPathIntoView(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView() method. ...
...he CanvasRenderingContext2D.scrollPathIntoView() method of the Canvas 2D API scrolls the current or given path into view. It is similar to Element.scrollIntoView(). Syntax void ctx.scrollPathIntoView(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView() method. ...
...nderingContext2D.scrollPathIntoView() method of the Canvas 2D API scrolls the current or given path into view. It is similar to Element.scrollIntoView(). Syntax void ctx.scrollPathIntoView(); void ctx.scrollPathIntoView(path); Parameters path A Path2D path to use. Examples Using the scrollPathIntoView method This example demonstrates the scrollPathIntoView() method. ...
...And 11 more matches
CanvasRenderingContext2D.shadowColor - Web APIs
Be aware that the shadow's rendered opacity will be affected by the opacity of the fillStyle color when filling, and of the strokeStyle color when stroking. Note: Shadows are only drawn if the shadowColor property is set to a non-transparent value. One of the shadowBlur, shadowOffsetX, or shadowOffsetY properties must be non-zero, as well. Syntax ctx.shadowColor = color; color A DOMString parsed as a CSS <color> value. The default value is fully-transparent black. Examples Adding a shadow to shapes This example adds a shadow to two squares; the first one is filled, and the second one is stroked. ...
...x.shadowColor = color; color A DOMString parsed as a CSS <color> value. The default value is fully-transparent black. Examples Adding a shadow to shapes This example adds a shadow to two squares; the first one is filled, and the second one is stroked. The shadowColor property sets the shadows' color, while shadowOffsetX and shadowOffsetY set their position relative to the shapes. ...
...or = color; color A DOMString parsed as a CSS <color> value. The default value is fully-transparent black. Examples Adding a shadow to shapes This example adds a shadow to two squares; the first one is filled, and the second one is stroked. The shadowColor property sets the shadows' color, while shadowOffsetX and shadowOffsetY set their position relative to the shapes. ...
...And 11 more matches
CanvasRenderingContext2D.createImageData() - Web APIs
All of the pixels in the new object are transparent black. Syntax ImageData ctx.createImageData(width, height); ImageData ctx.createImageData(imagedata); Parameters width The width to give the new ImageData object. A negative value flips the rectangle around the vertical axis. height The height to give the new ImageData object. A negative value flips the rectangle around the horizontal axis. imagedata An existing ImageData object from which to copy the width and height. The image itself is not copied. Return value A new ImageData object with the specified width and height. The new object is filled with transparent black pixels. ...
...ight. The image itself is not copied. Return value A new ImageData object with the specified width and height. The new object is filled with transparent black pixels. Errors thrown IndexSizeError Thrown if either of the width or height arguments is zero. Examples Creating a blank ImageData object This snippet creates a blank ImageData object using the createImageData() method. ...
...mage itself is not copied. Return value A new ImageData object with the specified width and height. The new object is filled with transparent black pixels. Errors thrown IndexSizeError Thrown if either of the width or height arguments is zero. Examples Creating a blank ImageData object This snippet creates a blank ImageData object using the createImageData() method. ...
...And 10 more matches
CanvasRenderingContext2D.ellipse() - Web APIs
Syntax void ctx.ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise]); The ellipse() method creates an elliptical arc centered at (x, y) with the radii radiusX and radiusY. The path starts at startAngle and ends at endAngle, and travels in the direction given by anticlockwise (defaulting to clockwise). Parameters x The x-axis (horizontal) coordinate of the ellipse's center. y The y-axis (vertical) coordinate of the ellipse's center. radiusX The ellipse's major-axis radius. Must be non-negative. radiusY The ellipse's minor-axis radius. Must be non-negative. rotation The rotation of the ellipse, expressed in radians. ...
...nd expressed in radians. anticlockwise Optional An optional Boolean which, if true, draws the ellipse anticlockwise (counter-clockwise). The default value is false (clockwise). Examples Drawing a full ellipse This example draws an ellipse at an angle of ?/4 radians (45?). To make a full ellipse, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). ...
...d in radians. anticlockwise Optional An optional Boolean which, if true, draws the ellipse anticlockwise (counter-clockwise). The default value is false (clockwise). Examples Drawing a full ellipse This example draws an ellipse at an angle of ?/4 radians (45?). To make a full ellipse, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). ...
...And 10 more matches
CanvasRenderingContext2D.putImageData() - Web APIs
If a dirty rectangle is provided, only the pixels from that rectangle are painted. This method is not affected by the canvas transformation matrix. Note: Image data can be retrieved from a canvas using the getImageData() method. You can find more information about putImageData() and general manipulation of canvas contents in the article Pixel manipulation with canvas. Syntax void ctx.putImageData(imageData, dx, dy); void ctx.putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight); Parameters imageData An ImageData object containing the array of pixel values. ...
... dirtyX Optional Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. Defaults to 0. dirtyY Optional Vertical position (y coordinate) of the top-left corner from which the image data will be extracted. Defaults to 0. ...
...void ctx.putImageData(imageData, dx, dy); void ctx.putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight); Parameters imageData An ImageData object containing the array of pixel values. dx Horizontal position (x coordinate) at which to place the image data in the destination canvas. dy Vertical position (y coordinate) at which to place the image data in the destination canvas. dirtyX Optional Horizontal position (x coordinate) of the top-left corner from which the image data will be extracted. Defaults to 0. dirtyY Optional Vertical position (y coordinate) of the top-left corner from which the image data will be extracted. Defaults to 0. dirtyWidth Optional Width of the rectangle to be painted. Defaults to the width of the image data. dirtyHeight Optional Heig...
...And 10 more matches
CanvasRenderingContext2D.stroke() - Web APIs
Strokes are aligned to the center of a path; in other words, half of the stroke is drawn on the inner side, and half on the outer side. The stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled. Syntax void ctx.stroke(); void ctx.stroke(path); Parameters path A Path2D path to stroke. Examples A simple stroked rectangle This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke(). ...
...he stroke is drawn on the inner side, and half on the outer side. The stroke is drawn using the non-zero winding rule, which means that path intersections will still get filled. Syntax void ctx.stroke(); void ctx.stroke(path); Parameters path A Path2D path to stroke. Examples A simple stroked rectangle This example creates a rectangle using the rect() method, and then draws it to the canvas using stroke(). HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); Result Re-stroking paths Typically, you'll want to call beginPath() for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked...
...('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); Result Re-stroking paths Typically, you'll want to call beginPath() for each new thing you want to stroke. If you don't, the previous sub-paths will remain part of the current path, and get stroked every time you call the stroke() method. In some cases, however, this may be the desired effect. HTML <canvas id="canvas"></canvas> JavaScript This code strokes the first path three times, the second path two times, and the third path only once. ...
...And 10 more matches
Canvas API - Web APIs
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 fillS...
... 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. ...
...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. ...
...And 10 more matches
HTMLCanvasElement - Web APIs
The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of <canvas> elements. The HTMLCanvasElement interface also inherits the properties and methods of the HTMLElement interface. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 20%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 120" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="mi...
...aco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLElement</text></a><polyline points="491,25 501,20 501,30 491,25" stroke="#D4DDE4" fill="none"/><line x1="501" y1="25" x2="509" y2="25" stroke="#D4DDE4"/><line x1="509" y1="25" x2="509" y2="90" stroke="#D4DDE4"/><line x1="509" y1="90" x2="492" y2="90" stroke="#D4DDE4"/><a xlink:href="/docs/Web/API/HTMLCanvasElement" target="_top"><rect x="321" y="65" width="170" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="406" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLCanvasElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits ...
...h="170" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="406" y="94" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLCanvasElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLCanvasElement.height The height HTML attribute of the <canvas> element is a positive integer reflecting the number of logical pixels (or RGBA values) going down one column of the canvas. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used. If no [separate] CSS height is assigned to the <canvas>, then this value will also be used as...
...And 10 more matches
CanvasRenderingContext2D.arc() - Web APIs
Syntax void ctx.arc(x, y, radius, startAngle, endAngle [, anticlockwise]); The arc() method creates a circular arc centered at (x, y) with a radius of radius. The path starts at startAngle, ends at endAngle, and travels in the direction given by anticlockwise (defaulting to clockwise). Parameters x The horizontal coordinate of the arc's center. y The vertical coordinate of the arc's center. radius The arc's radius. Must be positive. startAngle The angle at which the arc starts in radians, measured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise Optional An optional Boolean. ...
...arts in radians, measured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise Optional An optional Boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise). Examples Drawing a full circle This example draws a complete circle with the arc() method. ...
...adians, measured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise Optional An optional Boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise). Examples Drawing a full circle This example draws a complete circle with the arc() method. ...
...And 9 more matches
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
It requires three points: the first two are control points and the third one is the end point. The starting point is the latest point in the current path, which can be changed using moveTo() before creating the Bezier curve. Syntax void ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); Parameters cp1x The x-axis coordinate of the first control point. cp1y The y-axis coordinate of the first control point. cp2x The x-axis coordinate of the second control point. cp2y The y-axis coordinate of the second control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. ...
... coordinate of the first control point. cp1y The y-axis coordinate of the first control point. cp2x The x-axis coordinate of the second control point. cp2y The y-axis coordinate of the second control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How bezierCurveTo works This example shows how a cubic Bezier curve is drawn. ...
... of the first control point. cp1y The y-axis coordinate of the first control point. cp2x The x-axis coordinate of the second control point. cp2y The y-axis coordinate of the second control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How bezierCurveTo works This example shows how a cubic Bezier curve is drawn. ...
...And 9 more matches
CanvasRenderingContext2D.clearRect() - Web APIs
Note: Be aware that clearRect() may cause unintended side effects if you're not using paths properly. Make sure to call beginPath() before starting to draw new items after calling clearRect(). Syntax void ctx.clearRect(x, y, width, height); The clearRect() method sets the pixels in a rectangular area to transparent black (rgba(0,0,0,0)). The rectangle's corner is at (x, y), and its size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. ...
...r is at (x, y), and its size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. ...
... width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples Erasing the whole canvas This code snippet erases the entire canvas. ...
...And 9 more matches
CanvasRenderingContext2D.fillStyle - Web APIs
Examples Changing the fill color of a shape This example applies a blue fill color to a rectangle. ...
... Examples Changing the fill color of a shape This example applies a blue fill color to a rectangle. ...
... Examples Changing the fill color of a shape This example applies a blue fill color to a rectangle. ...
...And 9 more matches
CanvasRenderingContext2D.closePath() - Web APIs
If the shape has already been closed or has only one point, this function does nothing. This method doesn't draw anything to the canvas directly. You can render the path using the stroke() or fill() methods. Syntax void ctx.closePath(); Examples Closing a triangle This example creates the first two (diagonal) sides of a triangle using the lineTo() method. After that, the triangle's base is created with the closePath() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas> JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). ...
...draw anything to the canvas directly. You can render the path using the stroke() or fill() methods. Syntax void ctx.closePath(); Examples Closing a triangle This example creates the first two (diagonal) sides of a triangle using the lineTo() method. After that, the triangle's base is created with the closePath() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas> JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). ...
...closePath(); Examples Closing a triangle This example creates the first two (diagonal) sides of a triangle using the lineTo() method. After that, the triangle's base is created with the closePath() method, which automatically connects the shape's first and last points. HTML <canvas id="canvas"></canvas> JavaScript The triangle's corners are at (20, 150), (120, 20), and (220, 150). ...
...And 8 more matches
CanvasRenderingContext2D.createRadialGradient() - Web APIs
Parameters x0 The x-axis coordinate of the start circle. ...
... Parameters x0 The x-axis coordinate of the start circle. ...
... Parameters x0 The x-axis coordinate of the start circle. ...
...And 8 more matches
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
It requires two points: the first one is a control point and the second one is the end point. The starting point is the latest point in the current path, which can be changed using moveTo() before creating the quadratic Bezier curve. Syntax void ctx.quadraticCurveTo(cpx, cpy, x, y); Parameters cpx The x-axis coordinate of the control point. cpy The y-axis coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
...e creating the quadratic Bezier curve. Syntax void ctx.quadraticCurveTo(cpx, cpy, x, y); Parameters cpx The x-axis coordinate of the control point. cpy The y-axis coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
...the quadratic Bezier curve. Syntax void ctx.quadraticCurveTo(cpx, cpy, x, y); Parameters cpx The x-axis coordinate of the control point. cpy The y-axis coordinate of the control point. x The x-axis coordinate of the end point. y The y-axis coordinate of the end point. Examples How quadraticCurveTo works This example shows how a quadratic Bezier curve is drawn. ...
...And 8 more matches
Canvas size and WebGL - Web APIs
<< PreviousNext >> This WebGL example explores the effect of setting (or not setting) the canvas size to its element size in CSS pixels, as it appears in the browser window. Effect of canvas size on rendering with WebGL With scissor() and clear() we can demonstrate how the WebGL drawing buffer is affected by the size of the canvas. The size of the first canvas is set to the styled Element size, determined by CSS. This is done by assigning the width and height properties of the canvas to the values of the clientWidth and clientHeight properties, respectively. In contrast, no such assignment is done for the second canvas. ...
...L drawing buffer is affected by the size of the canvas. The size of the first canvas is set to the styled Element size, determined by CSS. This is done by assigning the width and height properties of the canvas to the values of the clientWidth and clientHeight properties, respectively. In contrast, no such assignment is done for the second canvas. The internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas Element in the browser window. The effect is clearly visible when using scissor() and clear() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position. <p>Compare t...
... at default values, which are different than the actual size of the canvas Element in the browser window. The effect is clearly visible when using scissor() and clear() to draw a square in the center of the canvas, by specifying its position and size in pixels. In the first canvas, we get the desired result. In the second, the square has the wrong shape, size, and position. ...
...And 8 more matches
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
Syntax void ctx.drawFocusIfNeeded(element); void ctx.drawFocusIfNeeded(path, element); Parameters element The element to check whether it is focused or not. path A Path2D path to use. Examples Managing button focus This example draws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
...wFocusIfNeeded() method of the Canvas 2D API draws a focus ring around the current or given path, if the specified element is focused. Syntax void ctx.drawFocusIfNeeded(element); void ctx.drawFocusIfNeeded(path, element); Parameters element The element to check whether it is focused or not. path A Path2D path to use. Examples Managing button focus This example draws two buttons on a canvas. ...
...th, if the specified element is focused. Syntax void ctx.drawFocusIfNeeded(element); void ctx.drawFocusIfNeeded(path, element); Parameters element The element to check whether it is focused or not. path A Path2D path to use. Examples Managing button focus This example draws two buttons on a canvas. The drawFocusIfNeeded() method is used to draw a focus ring when appropriate. ...
...And 7 more matches
CanvasRenderingContext2D.globalAlpha - Web APIs
Syntax ctx.globalAlpha = value; Options value A number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0. Values outside that range, including Infinity and NaN, will not be set, and globalAlpha will retain its previous value. Examples Drawing translucent shapes This example uses the globalAlpha property to draw two semi-transparent rectangles. ...
... ctx.globalAlpha = value; Options value A number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0. Values outside that range, including Infinity and NaN, will not be set, and globalAlpha will retain its previous value. Examples Drawing translucent shapes This example uses the globalAlpha property to draw two semi-transparent rectangles. ...
...Alpha = value; Options value A number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. The default value is 1.0. Values outside that range, including Infinity and NaN, will not be set, and globalAlpha will retain its previous value. Examples Drawing translucent shapes This example uses the globalAlpha property to draw two semi-transparent rectangles. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.globalAlpha = 0.5; ctx.fillStyle = 'blue'; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = 'red'; ctx.fillRect(50, 50, 100, 100); Result Overlaying transparent shapes This example illustrates the effect of overlaying multiple transparent shapes on top of each other. We begi...
...And 7 more matches
CanvasRenderingContext2D.scale() - Web APIs
By default, one unit on the canvas is exactly one pixel. A scaling transformation modifies this behavior. For instance, a scaling factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal size. Similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus drawn at twice the normal size. Syntax void ctx.scale(x, y); Parameters x Scaling factor in the horizontal direction. A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling. y Scaling factor in the vertical direction. ...
...izontal direction. A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling. y Scaling factor in the vertical direction. A negative value flips pixels across the horizontal axis. A value of 1 results in no vertical scaling. Examples Scaling a shape This example draws a scaled rectangle. A non-scaled rectangle is then drawn for comparison. ...
...ection. A negative value flips pixels across the vertical axis. A value of 1 results in no horizontal scaling. y Scaling factor in the vertical direction. A negative value flips pixels across the horizontal axis. A value of 1 results in no vertical scaling. Examples Scaling a shape This example draws a scaled rectangle. A non-scaled rectangle is then drawn for comparison. ...
...And 7 more matches
CanvasRenderingContext2D.setLineDash() - Web APIs
It uses an array of values that specify alternating lengths of lines and gaps which describe the pattern. Note: To return to using solid lines, set the line dash list to an empty array. Syntax ctx.setLineDash(segments); Parameters segments An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. ...
... the number of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. Examples Basic example This example uses the setLineDash() method to draw a dashed line above a solid line. ...
... of elements in the array is odd, the elements of the array get copied and concatenated. For example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is cleared and line strokes return to being solid. Return value undefined. Examples Basic example This example uses the setLineDash() method to draw a dashed line above a solid line. ...
...And 7 more matches
CanvasRenderingContext2D.strokeStyle - Web APIs
Examples Changing the stroke color of a shape This example applies a blue stroke color to a rectangle. ...
... Examples Changing the stroke color of a shape This example applies a blue stroke color to a rectangle. ...
... Examples Changing the stroke color of a shape This example applies a blue stroke color to a rectangle. ...
...And 7 more matches
HTMLCanvasElement.getContext() - Web APIs
The HTMLCanvasElement.getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported. Later calls to this method on the same canvas element return the same drawing context instance as was returned the last time the method was invoked with the same contextType argument. To get a different drawing context object you need to pass a different contextType or call the method on a different canvas element. Syntax var ctx = canvas.getContext(contextType); var ctx = canvas.getContext(contextType, contextAttributes); Parameters contextType Is a DOMString containing the context identifier defining the drawing context associated to the canvas. ...
...ct you need to pass a different contextType or call the method on a different canvas element. Syntax var ctx = canvas.getContext(contextType); var ctx = canvas.getContext(contextType, contextAttributes); Parameters contextType Is a DOMString containing the context identifier defining the drawing context associated to the canvas. Possible values are: "2d", leading to the creation of a CanvasRenderingContext2D object representing a two-dimensional rendering context. "webgl" (or "experimental-webgl") which will create a WebGLRenderingContext object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 1 (OpenGL ES 2.0). "webgl2" which will create a WebGL2RenderingContext object representing a three-dimensional re...
...e on browsers that implement WebGL version 1 (OpenGL ES 2.0). "webgl2" which will create a WebGL2RenderingContext object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 2 (OpenGL ES 3.0). "bitmaprenderer" which will create an ImageBitmapRenderingContext which only provides functionality to replace the content of the canvas with a given ImageBitmap. Note: The identifier "experimental-webgl" is used in new implementations of WebGL. These implementations have either not reached test suite conformance, or the graphics drivers on the platform are not yet stable. The Khronos Group certifies WebGL implementations under certain conformance rules. contextAttributes You can use several context attributes when c...
...And 7 more matches
OffscreenCanvas.getContext() - Web APIs
"webgl" creates a WebGLRenderingContext object representing a three-dimensional rendering context. ...
... "webgl" creates a WebGLRenderingContext object representing a three-dimensional rendering context. ...
...Possible values are: "2d" creates a CanvasRenderingContext2D object representing a two-dimensional rendering context. "webgl" creates a WebGLRenderingContext object representing a three-dimensional rendering context. This context is only available on browsers that implement WebGL version 1 (OpenGL ES 2.0). ...
...And 7 more matches
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
HTML provides a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin. See CORS settings attributes for details on how the crossorigin attribute is used. Security and tainted canvases Because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise. ...
... be used in a <canvas> as if they had been loaded from the current origin. See CORS settings attributes for details on how the crossorigin attribute is used. Security and tainted canvases Because the pixels in a canvas's bitmap can come from a variety of sources, including images or videos retrieved from other hosts, it's inevitable that security problems may arise. As soon as you draw into a canvas any data that was loaded from another origin without CORS approval, the canvas becomes tainted. A tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an exception to be thrown. If the source of the foreign content is an HTML <img> or SVG <svg> element, attempting to retrieve the contents of the canvas isn't allowed. ...
... canvas becomes tainted. A tainted canvas is one which is no longer considered secure, and any attempts to retrieve image data back from the canvas will cause an exception to be thrown. If the source of the foreign content is an HTML <img> or SVG <svg> element, attempting to retrieve the contents of the canvas isn't allowed. If the foreign content comes from an image obtained from either as HTMLCanvasElement or ImageBitMap, and the image source doesn't meet the same origin rules, attempts to read the canvas's contents are blocked. Calling any of the following on a tainted canvas will result in an error: Calling getImageData() on the canvas's context Calling toBlob() on the <canvas> element itself Calling toDataURL() on the canvas Attempting any of these when the canvas is tainted will ...
...And 7 more matches
CanvasGradient.addColorStop() - Web APIs
The gradient is then used to fill a rectangle. ...
... The CanvasGradient.addColorStop() method adds a new color stop, defined by an offset and a color, to a given canvas gradient. Syntax void gradient.addColorStop(offset, color); Parameters offset A number between 0 and 1, inclusive, representing the position of the color stop. 0 represents the start of the gradient and 1 represents the end; an INDEX_SIZE_ERR is raised if the number is outside that range. color A CSS <color> value representing the color of the stop. A SYNTAX_ERR is raised if the value cannot be parsed as a CSS <color> value. Examples Adding stops to a gradient This example uses the addColorStop method to add stops to a linear CanvasGradient object. ...
...the end; an INDEX_SIZE_ERR is raised if the number is outside that range. color A CSS <color> value representing the color of the stop. A SYNTAX_ERR is raised if the value cannot be parsed as a CSS <color> value. Examples Adding stops to a gradient This example uses the addColorStop method to add stops to a linear CanvasGradient object. The gradient is then used to fill a rectangle. ...
...And 6 more matches
CanvasRenderingContext2D.createLinearGradient() - Web APIs
Parameters x0 The x-axis coordinate of the start point. y0 The y-axis coordinate of the start point. ...
... Parameters x0 The x-axis coordinate of the start point. y0 The y-axis coordinate of the start point. ...
... a gradient along the line connecting two given coordinates. This method returns a linear CanvasGradient. To be applied to a shape, the gradient must first be assigned to the fillStyle or strokeStyle properties. Note: Gradient coordinates are global, i.e., relative to the current coordinate space. When applied to a shape, the coordinates are NOT relative to the shape's coordinates. Syntax CanvasGradient ctx.createLinearGradient(x0, y0, x1, y1); The createLinearGradient() method is specified by four parameters defining the start and end points of the gradient line. Parameters x0 The x-axis coordinate of the start point. y0 The y-axis coordinate of the start point. ...
...And 6 more matches
CanvasRenderingContext2D.fill() - Web APIs
Syntax void ctx.fill([fillRule]); void ctx.fill(path [, fillRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the filling region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to fill. Examples Filling a rectangle This example fills a rectangle with the fill() method. ...
...Rule]); void ctx.fill(path [, fillRule]); Parameters fillRule The algorithm by which to determine if a point is inside or outside the filling region. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to fill. Examples Filling a rectangle This example fills a rectangle with the fill() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the ...
...ctx = canvas.getContext('2d'); ctx.rect(10, 10, 150, 100); ctx.fill(); Result Specifying a path and a fillRule This example saves some intersecting lines to a Path2D object. The fill() method is then used to render the object to the canvas. A hole is left unfilled in the object's center by using the "evenodd" rule; by default (with the "nonzero" rule), the hole would also be filled. ...
...And 6 more matches
CanvasRenderingContext2D.lineCap - Web APIs
Note: Lines can be drawn with the stroke(), strokeRect(), and strokeText() methods. Syntax ctx.lineCap = "butt" || "round" || "square"; Options "butt" The ends of lines are squared off at the endpoints. Default value. "round" The ends of lines are rounded. "square" The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. Examples Changing the shape of line caps This example rounds the end caps of a straight line. ...
...neCap = "butt" || "round" || "square"; Options "butt" The ends of lines are squared off at the endpoints. Default value. "round" The ends of lines are rounded. "square" The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. Examples Changing the shape of line caps This example rounds the end caps of a straight line. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineWidth = 15; ctx.lineCap = 'round'; ctx.lineTo(100, 100); ctx.stroke(); Result Comparison of line caps In this example three lines are drawn, each with a different value for the lineCap property. Two guides to see the exact d...
...ines starts and ends exactly on these guides. The line on the left uses the default "butt" option. It's drawn completely flush with the guides. The second is set to use the "round" option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the "square" option. This adds a box with an equal width and half the height of the line thickness. ...
...And 6 more matches
CanvasRenderingContext2D.lineJoin - Web APIs
This property has no effect wherever two connected segments have the same direction, because no joining area will be added in this case. Degenerate segments with a length of zero (i.e., with all endpoints and control points at the exact same position) are also ignored. Note: Lines can be drawn with the stroke(), strokeRect(), and strokeText() methods. Syntax ctx.lineJoin = "bevel" || "round" || "miter"; Options There are three possible values for this property: "round", "bevel", and "miter". The default is "miter". ...
...ts, and the separate outside rectangular corners of each segment. "miter" Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is affected by the miterLimit property. Default value. Examples Changing the joins in a path This example applies rounded line joins to a path. ...
... separate outside rectangular corners of each segment. "miter" Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is affected by the miterLimit property. Default value. Examples Changing the joins in a path This example applies rounded line joins to a path. ...
...And 6 more matches
CanvasRenderingContext2D.lineTo() - Web APIs
Like other methods that modify the current path, this method does not directly render anything. To draw the path onto a canvas, you can use the fill() or stroke() methods. Syntax ctx.lineTo(x, y); Parameters x The x-axis coordinate of the line's end point. y The y-axis coordinate of the line's end point. Return value undefined. Examples Drawing a straight line This example draws a straight line using the lineTo() method. HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
...this method does not directly render anything. To draw the path onto a canvas, you can use the fill() or stroke() methods. Syntax ctx.lineTo(x, y); Parameters x The x-axis coordinate of the line's end point. y The y-axis coordinate of the line's end point. Return value undefined. Examples Drawing a straight line This example draws a straight line using the lineTo() method. HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
...or stroke() methods. Syntax ctx.lineTo(x, y); Parameters x The x-axis coordinate of the line's end point. y The y-axis coordinate of the line's end point. Return value undefined. Examples Drawing a straight line This example draws a straight line using the lineTo() method. HTML <canvas id="canvas"></canvas> JavaScript The line begins at (30, 50) and ends at (150, 100). ...
...And 6 more matches
CanvasRenderingContext2D.resetTransform() - Web APIs
Syntax void ctx.resetTransform(); Examples Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform() method. HTML <canvas id="canvas"></canvas> JavaScript The rotate() method rotates the transformation matrix by 45?. The fillRect() method draws a filled rectangle, adjusted according to that matrix. ...
...yntax void ctx.resetTransform(); Examples Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform() method. HTML <canvas id="canvas"></canvas> JavaScript The rotate() method rotates the transformation matrix by 45?. The fillRect() method draws a filled rectangle, adjusted according to that matrix. ...
... Examples Resetting the matrix This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform() method. HTML <canvas id="canvas"></canvas> JavaScript The rotate() method rotates the transformation matrix by 45?. The fillRect() method draws a filled rectangle, adjusted according to that matrix. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Draw a rotated rectangle ctx.rotate(45 * Math.PI / 180); ctx.fillRect(60, 0, 100, 30); // Reset transformation matrix to the identity matrix ctx.resetTransform(); Result Continuing with a regular matrix Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this example, the first two ...
...And 6 more matches
Manipulating video using canvas - Web APIs
This tutorial demonstrates how to perform chroma-keying (also known as the "green screen effect") using JavaScript code. The document content The HTML document used to render this content is shown below. ...
... Canvas c1 is used to display the current frame of the original video, while c2 is used to di...
... Canvas c1 is used to display the current frame of the original video, while c2 is used to display the video after performing the chro...
...And 6 more matches
Canvas - MDN Web Docs Glossary: Definitions of Web-related terms
The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D and 3D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph. It provides an empty graphic zone on which specific JavaScript APIs can draw (such as Canvas 2D or WebGL). ...
... The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D and 3D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph. It provides an empty graphic zone on which specific JavaScript APIs can draw (such as Canvas 2D or WebGL). ...
...s element is part of HTML5 and allows for dynamic, scriptable rendering of 2D and 3D shapes and bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in scene graph. It provides an empty graphic zone on which specific JavaScript APIs can draw (such as Canvas 2D or WebGL). ...
...And 5 more matches
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
On getting the imageSmoothingEnabled property, the last value it was set to is returned. This property is useful for games and other apps that use pixel art. When enlarging images, the default resizing algorithm will blur the pixels. Set this property to false to retain the pixels' sharpness. Note: You can adjust the smoothing quality with the imageSmoothingQuality property. Syntax ctx.imageSmoothingEnabled = value; Options value A Boolean indicating whether to smooth scaled images or not. The default value is true. ...
...SmoothingEnabled = value; Options value A Boolean indicating whether to smooth scaled images or not. The default value is true. Examples Disabling image smoothing This example compares three images. The first image is drawn at its natural size, the second is scaled to 3X and drawn with image smoothing enabled, and the third is scaled to 3X but drawn with image smoothing disabled. ...
...abled = value; Options value A Boolean indicating whether to smooth scaled images or not. The default value is true. Examples Disabling image smoothing This example compares three images. The first image is drawn at its natural size, the second is scaled to 3X and drawn with image smoothing enabled, and the third is scaled to 3X but drawn with image smoothing disabled. ...
...And 5 more matches
CanvasRenderingContext2D.strokeRect() - Web APIs
This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. Syntax void ctx.strokeRect(x, y, width, height); The strokeRect() method draws a stroked rectangle whose starting point is at (x, y) and whose size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. ...
...e of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple stroked rectangle This example draws a rectangle with a green outline using the strokeRect() method. ...
...ctangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple stroked rectangle This example draws a rectangle with a green outline using the strokeRect() method. HTML <canvas id="canvas"></canvas> JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 160 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.strokeStyle = 'green'; ctx.strokeRect(20, 10, 160, 100); Result Applying various context settings This example draws a rectangle with a drop shadow and thick, beveled outlines. HTML <...
...And 5 more matches
CanvasRenderingContext2D.textBaseline - Web APIs
Syntax ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom"; Options Possible values: "top" The text baseline is the top of the em square. "hanging" The text baseline is the hanging baseline. (Used by Tibetan and other Indic scripts.) "middle" The text baseline is the middle of the em square. "alphabetic" The text baseline is the normal alphabetic baseline. Default value. "ideographic" The text baseline is the ideographic baseline; this is the bottom of the body of the characters, if the main body of characters protrudes beneath the alphabetic baseline. ...
...h the alphabetic baseline. (Used by Chinese, Japanese, and Korean scripts.) "bottom" The text baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. The default value is "alphabetic". Examples Comparison of property values This example demonstrates the various textBaseline property values. ...
...betic baseline. (Used by Chinese, Japanese, and Korean scripts.) "bottom" The text baseline is the bottom of the bounding box. This differs from the ideographic baseline in that the ideographic baseline doesn't consider descenders. The default value is "alphabetic". Examples Comparison of property values This example demonstrates the various textBaseline property values. ...
...And 5 more matches
CanvasCaptureMediaStreamTrack - Web APIs
This lets applications that wish to specify the frame capture times directly do so, if they specified a frameRate of 0 when calling captureStream(). ...
...This lets applications that wish to specify the frame capture times directly do so, if they specified a frameRate of 0 when calling captureStream(). ...
...This lets applications that wish to specify the frame capture times directly do so, if they specified a frameRate of 0 when calling captureStream(). ...
...And 4 more matches
CanvasPattern.setTransform() - Web APIs
The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. ...
...ern.setTransform() method uses an SVGMatrix or DOMMatrix object as the pattern's transformation matrix and invokes it on the pattern. Syntax void pattern.setTransform(matrix); Parameters matrix An SVGMatrix or DOMMatrix to use as the pattern's transformation matrix. Examples Using the setTransform method This is just a simple code snippet which uses the setTransform method to create a CanvasPattern with the specified pattern transformation from an SVGMatrix. The pattern gets applied if you set it as the current fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. HTML <canvas id="canvas"></canvas> <svg id="svg1"></svg> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var svg1 = document.getElementBy...
...fillStyle and gets drawn onto the canvas when using the fillRect() method, for example. ...
...And 4 more matches
CanvasRenderingContext2D.currentTransform - Web APIs
Syntax ctx.currentTransform [= value]; value A DOMMatrix or SVGMatrix object to use as the current transformation matrix. Examples Manually changing the matrix This example uses the currentTransform property to set a transformation matrix. A rectangle is then drawn using that transformation. ...
...ion) or SVGMatrix (old specification) object for the current transformation matrix. Syntax ctx.currentTransform [= value]; value A DOMMatrix or SVGMatrix object to use as the current transformation matrix. ...
...Matrix (old specification) object for the current transformation matrix. Syntax ctx.currentTransform [= value]; value A DOMMatrix or SVGMatrix object to use as the current transformation matrix. ...
...And 4 more matches
CanvasRenderingContext2D.filter - Web APIs
It is similar to the CSS filter property and accepts the same values. Syntax ctx.filter = "<filter-function1> [<filter-function2>] [<filter-functionN>]"; ctx.filter = "none"; Values The filter property accepts a value of "none" or one or more of the following filter functions in a DOMString. url() A CSS <url>. Takes an IRI pointing to an SVG filter element, which may be embedded in an external XML file. blur() A CSS <length>. Applies a Gaussian blur to the drawing. It defines the value of the standard deviation to the Gaussian function, i.e., how many pixels on the screen blend into each other; thus, a larger value will create more blur. ...
...pia() A CSS <percentage>. Converts the drawing to sepia. A value of 100% means completely sepia. A value of 0% leaves the drawing unchanged. none No filter is applied. Initial value. Examples To view these examples, make sure to use a browser that supports this feature; see the compatibility table below. Applying a blur This example blurs a piece of text using the filter property. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.filter = 'blur(4px)'; ctx.font = '48px serif'; ctx.fillText('Hello world', 50, 100); Result Applying multiple filters You can combine as many filters as you like. This example applies the contrast, sepia, and drop-shadow filters to a photo of a gecko. HTML <canva...
...anvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.filter = 'blur(4px)'; ctx.font = '48px serif'; ctx.fillText('Hello world', 50, 100); Result Applying multiple filters You can combine as many filters as you like. This example applies the contrast, sepia, and drop-shadow filters to a photo of a gecko. ...
...And 4 more matches
CanvasRenderingContext2D.getImageData() - Web APIs
This method is not affected by the canvas's transformation matrix. If the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are transparent black in the returned ImageData object. Note: Image data can be painted onto a canvas using the putImageData() method. You can find more information about getImageData() and general manipulation of canvas contents in Pixel manipulation with canvas. Syntax ctx.getImageData(sx, sy, sw, sh); Parameters sx The x-axis coordinate of the top-left corner of the rectangle from which the ImageData will be extracted. ...
... Syntax ctx.getImageData(sx, sy, sw, sh); Parameters sx The x-axis coordinate of the top-left corner of the rectangle from which the ImageData will be extracted. sy The y-axis coordinate of the top-left corner of the rectangle from which the ImageData will be extracted. sw The width of the rectangle from which the ImageData will be extracted. ...
...ectangle from which the ImageData will be extracted. sw The width of the rectangle from which the ImageData will be extracted. Positive values are to the right, and negative to the left. sh The height of the rectangle from which the ImageData will be extracted. Positive values are down, and negative are up. Return value An ImageData object containing the image data for the rectangle of the canvas specified. The coordinates of the rectangle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh). Exceptions IndexSizeError Thrown if either sw or sh are zero. SecurityError The canvas contains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. To avoid SecurityError being thrown ...
...And 4 more matches
CanvasRenderingContext2D.getTransform() - Web APIs
The CanvasRenderingContext2D.getTransform() method of the Canvas 2D API retrieves the current transformation matrix being applied to the context. Syntax let storedTransform = ctx.getTransform(); Parameters None. Return value A DOMMatrix object. The transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] Note: The returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned DOMMatrix. Examples In the following example, we have two <canvas> elements. ...
... \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] Note: The returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned DOMMatrix. Examples In the following example, we have two <canvas> elements. We apply a transform to the first one's context using CanvasRenderingContext2D.setTransform() and draw a square on it, then retrieve the matrix from it using getTransform(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform(), and draw a circle on it. HTML <canvas width="240"></canvas> <canvas width="240"></canvas> CSS canvas { border: 1px solid black; } JavaScript co...
...eringContext2D.setTransform() and draw a square on it, then retrieve the matrix from it using getTransform(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform(), and draw a circle on it. ...
...And 4 more matches
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
The imageSmoothingQuality property of the CanvasRenderingContext2D interface, part of the Canvas API, lets you set the quality of image smoothing. Note: For this property to have an effect, imageSmoothingEnabled must be true. Syntax ctx.imageSmoothingQuality = "low" || "medium" || "high" Options Possible values: "low" Low quality. "medium" Medium quality. "high" High quality. Example Setting image smoothing quality This example uses the imageSmoothingQuality property with a scaled image. ...
...ality of image smoothing. Note: For this property to have an effect, imageSmoothingEnabled must be true. Syntax ctx.imageSmoothingQuality = "low" || "medium" || "high" Options Possible values: "low" Low quality. "medium" Medium quality. "high" High quality. Example Setting image smoothing quality This example uses the imageSmoothingQuality property with a scaled image. ...
...age smoothing. Note: For this property to have an effect, imageSmoothingEnabled must be true. Syntax ctx.imageSmoothingQuality = "low" || "medium" || "high" Options Possible values: "low" Low quality. "medium" Medium quality. "high" High quality. Example Setting image smoothing quality This example uses the imageSmoothingQuality property with a scaled image. ...
...And 4 more matches
CanvasRenderingContext2D.restore() - Web APIs
Syntax void ctx.restore(); Examples Restoring a saved state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
... Syntax void ctx.restore(); Examples Restoring a saved state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
...the drawing state stack. If there is no saved state, this method does nothing. Fore more information about the drawing state, see CanvasRenderingContext2D.save(). Syntax void ctx.restore(); Examples Restoring a saved state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
...And 4 more matches
CanvasRenderingContext2D.translate() - Web APIs
Syntax void ctx.translate(x, y); The translate() method adds a translation transformation to the current matrix by moving the canvas and its origin x units horizontally and y units vertically on the grid. Parameters x Distance to move in the horizontal direction. Positive values are to the right, and negative to the left. y Distance to move in the vertical direction. Positive values are down, and negative are up. Examples Moving a shape This example draws a square that is moved from its default position by the translate() method. An unmoved square of the same size is then drawn for comparison. ...
...x Distance to move in the horizontal direction. Positive values are to the right, and negative to the left. y Distance to move in the vertical direction. Positive values are down, and negative are up. Examples Moving a shape This example draws a square that is moved from its default position by the translate() method. An unmoved square of the same size is then drawn for comparison. ...
... to move in the horizontal direction. Positive values are to the right, and negative to the left. y Distance to move in the vertical direction. Positive values are down, and negative are up. Examples Moving a shape This example draws a square that is moved from its default position by the translate() method. An unmoved square of the same size is then drawn for comparison. ...
...And 4 more matches
HTMLCanvasElement.mozGetAsFile() - Web APIs
Syntax canvas.mozGetAsFile(name, type); Parameters name A DOMString indicating the file name to give the file representing the image file in memory. type Optional A DOMString which specifies the image file format to use when creating the new image file. The default type is image/png. For other options, see our Image file type and format guide. Return value A File object representing the image contained in the canvas. The file's data is entirely located in memory until such time as it is explicitly written to disk. ...
...le(name, type); Parameters name A DOMString indicating the file name to give the file representing the image file in memory. type Optional A DOMString which specifies the image file format to use when creating the new image file. The default type is image/png. For other options, see our Image file type and format guide. Return value A File object representing the image contained in the canvas. ...
... specifies the image file format to use when creating the new image file. The default type is image/png. For other options, see our Image file type and format guide. Return value A File object representing the image contained in the canvas. The file's data is entirely located in memory until such time as it is explicitly written to disk. Examples This example creates an image file from the <canvas> element on the page, then uses a FileReader to read the image data from the file. ...
...And 4 more matches
Create the Canvas and draw on it - Game development
<< PreviousNext >> This is the 1st step out of 10 of the Gamedev Canvas tutorial. You can find the source code as it should look after completing this lesson at Gamedev-Canvas-workshop/lesson1.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML and the <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element. ...
...is can be done using HTML and the <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Gamedev Canvas Workshop</title> <style> * { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="myCanvas" width="480" height="320"></canvas> <script> // JavaScript code goes here </script> </body> </html> We have a charset defined, <title> and some basic CSS in the header. The body contains <canvas> and <script> elemen...
...auto; } </style> </head> <body> <canvas id="myCanvas" width="480" height="320"></canvas> <script> // JavaScript code goes here </script> </body> </html> We have a charset defined, <title> and some basic CSS in the header. The body contains <canvas> and <script> elements -- we will render the game inside the first one and write the JavaScript code that controls it in the second one. The <canvas> element has an id of myCanvas to allow us to easily grab a reference to it, and it is 480 pixels wide and 320 pixels high. All the JavaScript code we will write in this tutorial will go between the opening <script> and closing </script> tags. Canvas basics To actually be able to render graphics on the <canvas> element, first we have to grab a reference to it in JavaScript. Add the following be...
...And 3 more matches
CanvasRenderingContext2D.beginPath() - Web APIs
Syntax void ctx.beginPath(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath() method is called before beginning each line, so that they may be drawn with different colors. ...
...of the Canvas 2D API starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path. Note: To create a new sub-path, i.e., one matching the current canvas state, you can use CanvasRenderingContext2D.moveTo(). Syntax void ctx.beginPath(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath() method is called before beginning each line, so that they may be drawn with different colors. ...
... i.e., one matching the current canvas state, you can use CanvasRenderingContext2D.moveTo(). Syntax void ctx.beginPath(); Examples Creating distinct paths This example creates two paths, each of which contains a single line. HTML <canvas id="canvas"></canvas> JavaScript The beginPath() method is called before beginning each line, so that they may be drawn with different colors. ...
...And 3 more matches
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
Syntax ctx.globalCompositeOperation = type; type is a String identifying which of the compositing or blending mode operations to use. Types Examples Changing the composite operation This example uses the globalCompositeOperation property to draw two rectangles that exclude themselves where they overlap. ...
...rawing new shapes. See also Compositing and clipping in the Canvas Tutorial. Syntax ctx.globalCompositeOperation = type; type is a String identifying which of the compositing or blending mode operations to use. Types Examples Changing the composite operation This example uses the globalCompositeOperation property to draw two rectangles that exclude themselves where they overlap. ...
...shapes. See also Compositing and clipping in the Canvas Tutorial. Syntax ctx.globalCompositeOperation = type; type is a String identifying which of the compositing or blending mode operations to use. Types Examples Changing the composite operation This example uses the globalCompositeOperation property to draw two rectangles that exclude themselves where they overlap. ...
...And 3 more matches
CanvasRenderingContext2D.miterLimit - Web APIs
The CanvasRenderingContext2D.miterLimit property of the Canvas 2D API sets the miter limit ratio. For more info about miters, see Applying styles and color in the Canvas tutorial. Syntax ctx.miterLimit = value; Options value A number specifying the miter limit ratio, in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. The default value is 10.0. Examples Using the miterLimit property See the chapter Applying styles and color in the Canvas tutorial for more information. Playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPat...
...re information. ...
...canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginPath(); ctx.moveTo(0,0); ctx.lineWidth = 15; ctx.lineTo(100, 100); ctx.stroke();</textarea> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var textarea = document.getElementById("code"); var reset = document.getElementById("reset"); var edit = document.getElementById("edit"); var code = textarea.value; function drawCanvas() { ctx.clearRect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addEventListener("click", function() { textarea.value = code; drawCanvas(); }); e...
...And 3 more matches
CanvasRenderingContext2D.save() - Web APIs
The drawing state The drawing state that gets saved onto a stack consists of: The current transformation matrix. The current clipping region. The current dash list. The current values of the following attributes: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. ...
...t, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. Syntax void ctx.save(); Examples Saving the drawing state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
...Offset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled. Syntax void ctx.save(); Examples Saving the drawing state This example uses the save() method to save the default state and restore() to restore it later, so that you are able to draw a rect with the default state later. ...
...And 3 more matches
CanvasRenderingContext2D.setTransform() - Web APIs
This lets you scale, rotate, translate (move), and skew the context. Note: See also the transform() method; instead of overriding the current transform matrix, it multiplies it with a given one. Syntax ctx.setTransform(a, b, c, d, e, f); ctx.setTransform(matrix); The transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] Parameters setTransform() has two types of parameter that it can accept. ...
...cal translation (moving). The newer type consists of a single parameter, matrix, representing a 2D transformation matrix to set (technically, a DOMMatrixInit object; any object will do as long as it contains the above components as properties). Examples Skewing a shape This example skews a rectangle both vertically (.2) and horizontally (.8). Scaling and translation remain unchanged. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setTransform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Retrieving and passing a DOMMatrix object In the following example, we have two <canvas> elements. We apply a transform to the first one's context using the first type of setTransform() and draw...
...ment.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setTransform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Retrieving and passing a DOMMatrix object In the following example, we have two <canvas> elements. We apply a transform to the first one's context using the first type of setTransform() and draw a square on it, then retrieve the matrix from it using CanvasRenderingContext2D.getTransform(). We then apply the retrieved matrix directly to the second canvas context by passing the DOMMatrix object directly to setTransform() (i.e. the second type), and draw a circle on it. HTML <canvas width="240"></canvas> <canvas width="240"></canvas> CSS canvas { border: 1px solid black; } JavaScript const canvases = document.querySelectorAll('canvas'); cons...
...And 3 more matches
CanvasRenderingContext2D.shadowOffsetX - Web APIs
Note: Shadows are only drawn if the shadowColor property is set to a non-transparent value. One of the shadowBlur, shadowOffsetX, or shadowOffsetY properties must be non-zero, as well. Syntax ctx.shadowOffsetX = offset; offset A float specifying the distance that shadows will be offset horizontally. Positive values are to the right, and negative to the left. The default value is 0 (no horizontal offset). Infinity and NaN values are ignored. Examples Moving a shadow horizontally This example adds a blurred shadow to a rectangle. ...
...et horizontally. Positive values are to the right, and negative to the left. The default value is 0 (no horizontal offset). Infinity and NaN values are ignored. Examples Moving a shadow horizontally This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetX sets its offset 25 units to the right, and shadowBlur gives it a blur level of 10. ...
...ally. Positive values are to the right, and negative to the left. The default value is 0 (no horizontal offset). Infinity and NaN values are ignored. Examples Moving a shadow horizontally This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetX sets its offset 25 units to the right, and shadowBlur gives it a blur level of 10. ...
...And 3 more matches
CanvasRenderingContext2D.shadowOffsetY - Web APIs
Note: Shadows are only drawn if the shadowColor property is set to a non-transparent value. One of the shadowBlur, shadowOffsetX, or shadowOffsetY properties must be non-zero, as well. Syntax ctx.shadowOffsetY = offset; offset A float specifying the distance that shadows will be offset vertically. Positive values are down, and negative are up. The default value is 0 (no vertical offset). Infinity and NaN values are ignored. Examples Moving a shadow vertically This example adds a blurred shadow to a rectangle. ...
... will be offset vertically. Positive values are down, and negative are up. The default value is 0 (no vertical offset). Infinity and NaN values are ignored. Examples Moving a shadow vertically This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetY sets its offset 25 units towards the bottom, and shadowBlur gives it a blur level of 10. ...
...fset vertically. Positive values are down, and negative are up. The default value is 0 (no vertical offset). Infinity and NaN values are ignored. Examples Moving a shadow vertically This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, shadowOffsetY sets its offset 25 units towards the bottom, and shadowBlur gives it a blur level of 10. ...
...And 3 more matches
HTMLCanvasElement.mozFetchAsStream() - Web APIs
However, this non-standard and internal method has been removed. Syntax void canvas.mozFetchAsStream(callback, type); Parameters callback An nsIInputStreamCallback. type Optional A DOMString indicating the image format. The default type is image/png. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
...n nsIInputStreamCallback. type Optional A DOMString indicating the image format. The default type is image/png. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
...tional A DOMString indicating the image format. The default type is image/png. Return value None. Examples Save to disk with mozFetchAsStream (Chrome context only) This technique also converts it to ico, however it will not work in Windows XP as WinXP cannot convert from PNG to ICO. It saves to the desktop it uses FileUtils.jsm. ...
...And 3 more matches
Building up a basic demo with PlayCanvas editor - Game development
You can finish this before you continue our tutorial if you like. ...
...You can finish this before you continue our tutorial if you like. ...
...ode. Creating an account The PlayCanvas Editor is free -- all you have to do to begin with is register your account and login: When you first sign up, you are taken straight into the editor and given a simple starter tutorial involving editing a 3D rolling ball game. You can finish this before you continue our tutorial if you like. When you are ready to continue with our tutorial, go to your canvas homepage -- for example mine is https://playcanvas.com/end3r. Here's what the page looks like -- you can create projects and manage them, change their settings etc. Creating a new project Start a brand new project by clicking on the New button: The resulting dialog box will show a few different options. There are starter kits available, but we don't want to load models or start a platform ga...
...And 2 more matches
Building up a basic demo with PlayCanvas - Game development
Tanx is a multiplayer tank game where you can drive your tank around, shooting at other players as you go. Swooop is a flying game where you pilot your plane around a magical island, collecting jewels and fuel as you go. Visualizations like the Star Lord and BMW i8 also take advantage of the engine and showcase what's possible. ...
... Tanx is a multiplayer tank game where you can drive your tank around, shooting at other players as you go. Swooop is a flying game where you pilot your plane around a magical island, collecting jewels and fuel as you go. Visualizations like the Star Lord and BMW i8 also take advantage of the engine and showcase what's possible. ...
...lecting jewels and fuel as you go. Visualizations like the Star Lord and BMW i8 also take advantage of the engine and showcase what's possible. Note: Check out the list of featured demos to find more examples. ...
...And 2 more matches
CanvasCaptureMediaStreamTrack.requestFrame() - Web APIs
Applications that need to carefully control the timing of rendering and frame capture can use requestFrame() to directly specify when it's time to capture a frame. To prevent automatic capture of frames, so that frames are only captured when requestFrame() is called, specify a value of 0 for the captureStream() method when creating the stream. Syntax stream.requestFrame(); Return value undefined Usage notes There is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. ...
... capture a frame. To prevent automatic capture of frames, so that frames are only captured when requestFrame() is called, specify a value of 0 for the captureStream() method when creating the stream. ...
...s There is currently an issue flagged in the specification pointing out that at this time, no exceptions are being thrown if the canvas isn't origin-clean. This may change in the future, so it would be wise to plan ahead and watch for exceptions such as SecurityError (although the specific error that might be thrown is not mentioned in the spec, this is a likely candidate). ...
...And 2 more matches
CanvasRenderingContext2D.fillText() - Web APIs
The CanvasRenderingContext2D method fillText(), part of the Canvas 2D API, draws a text string at the specified coordinates, filling the string's characters with the current fillStyle. An optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size. This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. The text is rendered using the font and text layout configuration as defined by the font, textAlign, textBaseline, and direction properties. To draw the outlines of the characters in a string, call the context's strokeText() method. ...
...size. This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. The text is rendered using the font and text layout configuration as defined by the font, textAlign, textBaseline, and direction properties. To draw the outlines of the characters in a string, call the context's strokeText() method. Syntax CanvasRenderingContext2D.fillText(text, x, y [, maxWidth]); Parameters text A DOMString specifying the text string to render into the context. The text is rendered using the settings specified by font, textAlign, textBaseline, and direction. x The x-axis coordinate of the point at which to begin drawing the text, in pixels. y The y-axis coordinate of the point at which to begin drawing the tex...
...rovided, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing filled text This example writes the words "Hello world" using the fillText() method. ...
...And 2 more matches
CanvasRenderingContext2D.rect() - Web APIs
Like other methods that modify the current path, this method does not directly render anything. To draw the rectangle onto a canvas, you can use the fill() or stroke() methods. Note: To both create and render a rectangle in one step, use the fillRect() or strokeRect() methods. Syntax void ctx.rect(x, y, width, height); The rect() method creates a rectangular path whose starting point is at (x, y) and whose size is specified by width and height. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. ...
...ing point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples Drawing a rectangle This example creates a rectangular path using the rect() method. The path is then rendered using the fill() method. ...
... y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples Drawing a rectangle This example creates a rectangular path using the rect() method. The path is then rendered using the fill() method. ...
...And 2 more matches
CanvasRenderingContext2D.shadowBlur - Web APIs
The default is 0 (no blur). Note: Shadows are only drawn if the shadowColor property is set to a non-transparent value. One of the shadowBlur, shadowOffsetX, or shadowOffsetY properties must be non-zero, as well. Syntax ctx.shadowBlur = level; level A non-negative float specifying the level of shadow blur, where 0 represents no blur and larger numbers represent increasingly more blur. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. The default value is 0. Negative, Infinity, and NaN values are ignored. Examples Adding a shadow to a shape This example adds a blurred shadow to a rectangle. ...
...epresent increasingly more blur. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. The default value is 0. Negative, Infinity, and NaN values are ignored. Examples Adding a shadow to a shape This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, and shadowBlur sets its level of bluriness. ...
...creasingly more blur. This value doesn't correspond to a number of pixels, and is not affected by the current transformation matrix. The default value is 0. Negative, Infinity, and NaN values are ignored. Examples Adding a shadow to a shape This example adds a blurred shadow to a rectangle. The shadowColor property sets its color, and shadowBlur sets its level of bluriness. ...
...And 2 more matches
HTMLCanvasElement.captureStream() - Web APIs
Exceptions NotSupportedError The value of frameRate is negative. ...
... Exceptions NotSupportedError The value of frameRate is negative. ...
... The HTMLCanvasElement captureStream() method returns a MediaStream which includes a CanvasCaptureMediaStreamTrack containing a real-time video capture of the canvas's contents. Syntax MediaStream = canvas.captureStream(frameRate); Parameters frameRate Optional A double-precision floating-point value that indicates the rate of capture of each frame. If not set, a new frame will be captured each time the canvas changes; if set to 0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestFrame() method is called. ...
...And 2 more matches
CanvasImageSource - Web APIs
Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
...nism for other interfaces to be used as image sources for some methods of the CanvasDrawImage and CanvasFillStrokeStyles interfaces. It's just an internal helper type to simplify the specification. It's not an interface and there are no objects implementing it. The interfaces that it allows to be used as image sources are the following: HTMLImageElement SVGImageElement HTMLVideoElement HTMLCanvasElement ImageBitmap OffscreenCanvas Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasImageSource' in that specification. Living Standard Initial definition. ...
CanvasPattern - Web APIs
Living Standard Added setTransform() method in v5. ...
... It can be used as a fillStyle or strokeStyle. Properties As an opaque object, this has no exposed property. Methods There are no inherited method. CanvasPattern.setTransform() Applies an SVGMatrix or DOMMatrix representing a linear transform to the pattern. ...
... Living Standard Added setTransform() method in v5. ...
...ePattern() method. It can be used as a fillStyle or strokeStyle. Properties As an opaque object, this has no exposed property. Methods There are no inherited method. CanvasPattern.setTransform() Applies an SVGMatrix or DOMMatrix representing a linear transform to the pattern. Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasPattern' in that specification. Living Standard Added setTransform() method in v5. ...
CanvasRenderingContext2D.drawWindow() - Web APIs
The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling. This API cannot be used by Web content. It is synchronous, and as such can't be compatible with Fission. If you're using it from an extension, you should switch to tabs.captureTab. If you're writing chrome code, you probably want WindowGlobalParent.drawSnapshot from the parent process. Syntax void ctx.drawWindow(window, x, y, w, h, bgColor [, flags]); Parameters window The Window to render. x The x-axis coordinate of the window. y The y-axis coordinate of the window. ...
...ting chrome code, you probably want WindowGlobalParent.drawSnapshot from the parent process. Syntax void ctx.drawWindow(window, x, y, w, h, bgColor [, flags]); Parameters window The Window to render. x The x-axis coordinate of the window. y The y-axis coordinate of the window. w The width of the window. h The height of the window. bgColor A DOMString that specifies the color the canvas is filled with before the window is rendered into it. This color may be transparent/translucent. It is given as a CSS color string (for example, rgb() or rgba()). Notes: If "rgba(0,0,0,0)" is used for the background color, the drawing will be transparent wherever the window is transparent. Top-level browsed documents are usually not transparent because the user's background-color preferenc...
...available. This means hardware acceleration may be used, but it might actually be slower or lower quality than normal. It will, however, more accurately reflect the pixels rendered to the screen. DRAWWINDOW_ASYNC_DECODE_IMAGES 0x10 Do not synchronously decode images - draw what we have. Example This method draws a snapshot of the contents of a DOM window into the canvas. For example, ctx.drawWindow(window, 0, 0, 100, 200, 'rgb(255,255,255)'); ... would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a white background, into the canvas. By specifying "rgba(255,255,255,0)" as the color, the contents would be drawn with a transparent background (which would be slower). It is usually ...
...hich would be slower). It is usually a bad idea to use any background other than pure white "rgb(255,255,255)" or transparent, as this is what all browsers do, and many websites expect that transparent parts of their interface will be drawn on white background. With this method, it is possible to fill a hidden IFRAME with arbitrary content (e.g., CSS-styled HTML text, or SVG) and draw it into a canvas. It will be scaled, rotated and so on according to the current transformation. Ted Mielczarek's tab preview extension uses this technique in chrome to provide thumbnails of web pages, and the source is available for reference. Specifications Not part of any current specification or draft. This is a non-standard and internal only API. ...
CanvasRenderingContext2D.moveTo() - Web APIs
Syntax void ctx.moveTo(x, y); Parameters x The x-axis (horizontal) coordinate of the point. y The y-axis (vertical) coordinate of the point. Examples Creating multiple sub-paths This example uses moveTo() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke() call. HTML <canvas id="canvas"></canvas> JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). ...
... specified by the given (x, y) coordinates. Syntax void ctx.moveTo(x, y); Parameters x The x-axis (horizontal) coordinate of the point. y The y-axis (vertical) coordinate of the point. Examples Creating multiple sub-paths This example uses moveTo() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke() call. ...
... y The y-axis (vertical) coordinate of the point. Examples Creating multiple sub-paths This example uses moveTo() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke() call. HTML <canvas id="canvas"></canvas> JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). ...
...ate of the point. Examples Creating multiple sub-paths This example uses moveTo() to create two sub-paths within a single path. Both sub-paths are then rendered with a single stroke() call. HTML <canvas id="canvas"></canvas> JavaScript The first line begins at (50, 50) and ends at (200, 50). The second line begins at (50, 90) and ends at (280, 120). var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(50, 50); // Begin first sub-path ctx.lineTo(200, 50); ctx.moveTo(50, 90); // Begin second sub-path ctx.lineTo(280, 120); ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.moveTo' in that specification. Living Standar...
CanvasRenderingContext2D.strokeText() - Web APIs
The CanvasRenderingContext2D method strokeText(), part of the Canvas 2D API, strokes -- that is, draws the outlines of -- the characters of a text string at the specified coordinates. An optional parameter allows specifying a maximum width for the rendered text, which the user agent will achieve by condensing the text or by using a lower font size. This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. Use the fillText() method to fill the text characters rather than having just their outlines drawn. Syntax CanvasRenderingContext2D.strokeText(text, x, y [, maxWidth]); Parameters text A DOMString specifying the text string to render into the context. The text is rendered using the settings spe...
...d, the user agent will adjust the kerning, select a more horizontally condensed font (if one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing text outlines This example writes the words "Hello world" using the strokeText() method. ...
... one is available or can be generated without loss of quality), or scale down to a smaller font size in order to fit the text in the specified width. Return value undefined. Examples Drawing text outlines This example writes the words "Hello world" using the strokeText() method. HTML First, we need a canvas to draw into. This code creates a context 400 pixels wide and 150 pixels high. <canvas id="canvas" width="400" height="150"></canvas> JavaScript The JavaScript code for this example follows. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90); This code obtains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 5...
...tains a reference to the <canvas>, then gets a reference to its 2D graphics context. With that in hand, we set the font to 50-pixel-tall "serif" (the user's default serif font), then call strokeText() to draw the text "Hello world," starting at the coordinates (50, 90). Result Restricting the text size This example writes the words "Hello world," restricting its width to 140 pixels. HTML <canvas id="canvas" width="400" height="150"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '50px serif'; ctx.strokeText('Hello world', 50, 90, 140); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.strokeText' in that specification. ...
HTMLCanvasElement.mozOpaque - Web APIs
Use of mozOpaque should be avoided. Firefox will stop supporting it in the future. Syntax var opaque = canvas.mozOpaque; canvas.mozOpaque = true; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. ...
...Use of mozOpaque should be avoided. Firefox will stop supporting it in the future. Syntax var opaque = canvas.mozOpaque; canvas.mozOpaque = true; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. ...
...ement. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This has been standardized as setting the alpha option to false when creating a drawing context with HTMLCanvasElement.getContext(). Use of mozOpaque should be avoided. Firefox will stop supporting it in the future. Syntax var opaque = canvas.mozOpaque; canvas.mozOpaque = true; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. For example, you could conditionally set it to true if mimeType == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed. ...
...he future. Syntax var opaque = canvas.mozOpaque; canvas.mozOpaque = true; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. For example, you could conditionally set it to true if mimeType == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed. var canvas = document.getElementById('canvas'); console.log(canvas.mozOpaque); // true // deactivate it canvas.mozOpaque = false; Specifications Not part of any standard. ...
OffscreenCanvas.convertToBlob() - Web APIs
The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...ons: type: A DOMString indicating the image format. The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. Return value A Promise returning a Blob object representing the image contained in the canvas. Examples var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... offscreen.convertToBlob().then(function(blob) { console.log(blob); }); // Blob { size: 334, type: "image/png" } Specifications Currently drafted as a proposal: OffscreenCanvas. ...
OffscreenCanvas.convertToBlob() - Web APIs
The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...ons: type: A DOMString indicating the image format. The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. Return value A Promise returning a Blob object representing the image contained in the canvas. Examples var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... offscreen.convertToBlob().then(function(blob) { console.log(blob); }); // Blob { size: 334, type: "image/png" } Specifications Specification Status Comment HTML Living StandardThe definition of 'OffscreenCanvas: convertT...
OffscreenCanvas.convertToBlob() - Web APIs
The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. ...
...ons: type: A DOMString indicating the image format. The default type is image/png. quality: A Number between 0 and 1 indicating image quality if the type option is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored. Return value A Promise returning a Blob object representing the image contained in the canvas. Examples var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... offscreen.convertToBlob().then(function(blob) { console.log(blob); }); // Blob { size: 334, type: "image/png" } Specifications Currently drafted as a proposal: OffscreenCanvas. ...
CanvasRenderingContext2D.direction - Web APIs
Syntax ctx.direction = "ltr" || "rtl" || "inherit"; Options Possible values: "ltr" The text direction is left-to-right. "rtl" The text direction is right-to-left. "inherit" The text direction is inherited from the <canvas> element or the Document as appropriate. Default value. The default value is "inherit". Examples Changing text direction This example draws two pieces of text. The first one is left-to-right, and the second is right-to-left. Note that "Hi!" in ltr becomes "!Hi" in rtl. ...
...-to-right. "rtl" The text direction is right-to-left. "inherit" The text direction is inherited from the <canvas> element or the Document as appropriate. Default value. The default value is "inherit". Examples Changing text direction This example draws two pieces of text. The first one is left-to-right, and the second is right-to-left. Note that "Hi!" in ltr becomes "!Hi" in rtl. ...
... "rtl" The text direction is right-to-left. "inherit" The text direction is inherited from the <canvas> element or the Document as appropriate. Default value. The default value is "inherit". Examples Changing text direction This example draws two pieces of text. The first one is left-to-right, and the second is right-to-left. Note that "Hi!" in ltr becomes "!Hi" in rtl. HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.font = '48px serif'; ctx.fillText('Hi!', 150, 50); ctx.direction = 'rtl'; ctx.fillText('Hi!', 150, 130); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.direction' in that specification. ...
CanvasRenderingContext2D.fillRect() - Web APIs
This method draws directly to the canvas without modifying the current path, so any subsequent fill() or stroke() calls will have no effect on it. Syntax void ctx.fillRect(x, y, width, height); The fillRect() method draws a filled rectangle whose starting point is at (x, y) and whose size is specified by width and height. The fill style is determined by the current fillStyle attribute. Parameters x The x-axis coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. ...
...s coordinate of the rectangle's starting point. y The y-axis coordinate of the rectangle's starting point. width The rectangle's width. Positive values are to the right, and negative to the left. height The rectangle's height. Positive values are down, and negative are up. Examples A simple filled rectangle This example draws a filled green rectangle using the fillRect() method. HTML <canvas id="canvas"></canvas> JavaScript The rectangle's top-left corner is at (20, 10). It has a width of 150 and a height of 100. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(20, 10, 150, 100); Result Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This is often useful for crea...
...vas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = 'green'; ctx.fillRect(20, 10, 150, 100); Result Filling the whole canvas This code snippet fills the entire canvas with a rectangle. This is often useful for creating a background, on top of which other things may then be drawn. To achieve this, the dimensions of the rectangle are set to equal the <canvas> element's width and height attributes. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.fillRect(0, 0, canvas.width, canvas.height); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.fillRect' in that specification. Living Standard ...
CanvasRenderingContext2D.getLineDash() - Web APIs
Syntax ctx.getLineDash(); Return value An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number, when setting the elements, is odd, the elements of the array get copied and concatenated. For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. Examples Getting the current line dash setting This example demonstrates the getLineDash() method. HTML <canvas id="canvas"></canvas> JavaScript As set by setLineDash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. ...
...and concatenated. For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. Examples Getting the current line dash setting This example demonstrates the getLineDash() method. HTML <canvas id="canvas"></canvas> JavaScript As set by setLineDash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. ...
...ting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25]. Examples Getting the current line dash setting This example demonstrates the getLineDash() method. HTML <canvas id="canvas"></canvas> JavaScript As set by setLineDash(), strokes consist of lines that are 10 units wide, with spaces of 20 units in between each line. const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.setLineDash([10, 20]); console.log(ctx.getLineDash()); // [10, 20] // Draw a dashed line ctx.beginPath(); ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.getLineDash' in that specification. Living S...
CanvasRenderingContext2D.lineWidth - Web APIs
Note: Lines can be drawn with the stroke(), strokeRect(), and strokeText() methods. Syntax ctx.lineWidth = value; Options value A number specifying the line width, in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. This value is 1.0 by default. Examples Changing line width This example draws a line and a rectangle, using a line width of 15 units. ...
... Note: Lines can be drawn with the stroke(), strokeRect(), and strokeText() methods. Syntax ctx.lineWidth = value; Options value A number specifying the line width, in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. This value is 1.0 by default. Examples Changing line width This example draws a line and a rectangle, using a line width of 15 units. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.lineWidth = 15; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); Result More examples For more examples and explanation about this property, see Applying styles and color in the Canvas Tutorial. Specifications ...
... Living Standard ...
Canvas tutorial - Web APIs
<canvas> 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 (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial. This tutorial describes how to use the <canvas> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas about what you can do with canvas, and will provide code snippets that may get you started in building your own content. First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it. ...
...o draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas about what you can do with canvas, and will provide code snippets that may get you started in building your own content. First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it. Before you start Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> 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 x 150 pixels (width x height). But custom sizes can be defined using the HTML height and width property. In order to draw graphics on the c...
...he 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. ...
HTMLCanvasElement.height - Web APIs
The HTMLCanvasElement.height property is a positive integer reflecting the height HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used. This is one of the two properties, the other being HTMLCanvasElement.width, that controls the size of the canvas. Syntax var pxl = canvas.height; canvas.height = pxl; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get the height of the canvas with the following code: var canvas = document.getElementById('canvas'); console.log(canvas.height); // 300 Specifications Specification Status Comment HTML Living StandardThe definitio...
... Recommendation Snapshot of the HTML Living Standard containing the initial definition. ...
...t the height of the canvas with the following code: var canvas = document.getElementById('canvas'); console.log(canvas.height); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.height' in that specification. Living Standard No change since the latest snapshot, HTML5 HTML 5.1The definition of 'HTMLCanvasElement.height' in that specification. Recommendation HTML5The definition of 'HTMLCanvasElement.height' in that specification. Recommendation Snapshot of the HTML Living Standard containing the initial definition. ...
HTMLCanvasElement.width - Web APIs
The HTMLCanvasElement.width property is a positive integer reflecting the width HTML attribute of the <canvas> element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used. This is one of the two properties, the other being HTMLCanvasElement.height, that controls the size of the canvas. Syntax var pxl = canvas.width; canvas.width = pxl; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300"></canvas> You can get the width of the canvas with the following code: var canvas = document.getElementById('canvas'); console.log(canvas.width); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of ...
... Recommendation Snapshot of the HTML Living Standard containing the initial definition. ...
... get the width of the canvas with the following code: var canvas = document.getElementById('canvas'); console.log(canvas.width); // 300 Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.width' in that specification. Living Standard No change since the latest snapshot, HTML5 HTML 5.1The definition of 'HTMLCanvasElement.width' in that specification. Recommendation HTML5The definition of 'HTMLCanvasElement.width' in that specification. Recommendation Snapshot of the HTML Living Standard containing the initial definition. ...
WebGLRenderingContext.canvas - Web APIs
The WebGLRenderingContext.canvas property is a read-only reference to the HTMLCanvasElement or OffscreenCanvas object that is associated with the context. It might be null if it is not associated with a <canvas> element or an OffscreenCanvas object. Syntax gl.canvas; Return value Either a HTMLCanvasElement or OffscreenCanvas object or null. Examples Canvas element Given this <canvas> element: <canvas id="canvas"></canvas> You can get back a reference to it from the WebGLRenderingContext using the canvas property: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.canvas; // HTMLCanvasElement Offscreen canvas Example using the experimental OffscreenCanvas object. var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext('webg...
... Recommendation Initial definition. ...
... You can get back a reference to it from the WebGLRenderingContext using the canvas property: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.canvas; // HTMLCanvasElement Offscreen canvas Example using the experimental OffscreenCanvas object. var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext('webgl'); gl.canvas; // OffscreenCanvas Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.canvas' in that specification. Recommendation Initial definition. ...
nsIDOMCanvasRenderingContext2D
See that page for details. ...
...See that page for details. ...
CanvasRenderingContext2D.font - Web APIs
This string uses the same syntax as the CSS font specifier. Syntax ctx.font = value; Options value A DOMString parsed as CSS font value. The default font is 10px sans-serif. Examples Using a custom font In this example we use the font property to specify a custom font weight, size, and family. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = 'bold 48px serif'; ctx.strokeText('Hello world', 50, 100); Result Loading fonts with the CSS Font Loading API With the help of the FontFace API, you can explicitly load fonts before using them in a canvas. ...
...ecify a custom font weight, size, and family. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = 'bold 48px serif'; ctx.strokeText('Hello world', 50, 100); Result Loading fonts with the CSS Font Loading API With the help of the FontFace API, you can explicitly load fonts before using them in a canvas. let f = new FontFace('test', 'url(x)'); f.load().then(function() { // Ready to use the font in a canvas context }); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.font' in that specification. Living Standard ...
CanvasRenderingContext2D.transform() - Web APIs
This lets you scale, rotate, translate (move), and skew the context. Note: See also the setTransform() method, which resets the current transform to the identity matrix and then invokes transform(). Syntax void ctx.transform(a, b, c, d, e, f); The transformation matrix is described by: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right] Parameters a (m11) Horizontal scaling. A value of 1 results in no scaling. b (m12) Vertical skewing. c (m21) Horizontal skewing. d (m22) Vertical scaling. A value of 1 results in no scaling. e (dx) Horizontal translation (moving). ...
...ling. A value of 1 results in no scaling. b (m12) Vertical skewing. c (m21) Horizontal skewing. d (m22) Vertical scaling. A value of 1 results in no scaling. e (dx) Horizontal translation (moving). f (dy) Vertical translation (moving). Examples Skewing a shape This example skews a rectangle both vertically (.2) and horizontally (.8). Scaling and translation remain unchanged. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.transform(1, .2, .8, 1, 0, 0); ctx.fillRect(0, 0, 100, 100); Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.transform' in that specification. Living Standard ...
HTMLCanvasElement: webglcontextcreationerror event - Web APIs
nt of the WebGL API is fired if the user agent is unable to create a WebGLRenderingContext context. This event has a WebGLContextEvent.statusMessage property, which can contain a platform dependent string with more information about the failure. ...
...e user agent is unable to create a WebGLRenderingContext context. This event has a WebGLContextEvent.statusMessage property, which can contain a platform dependent string with more information about the failure. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example var canvas = document.getElementById('canvas'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log(e.statusMessage || 'Unknown error'); }, false); var gl = canvas.getContext('webgl'); // logs statusMessage or "Unknown error" if unable to create WebGL context Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextcreationerror' in that specification. R...
SVG And Canvas In Mozilla - Archive of obsolete content
ics capabilities to Web developers. Advances in hardware, especially graphics processors, offer the potential for far richer graphics in interactive applications. To realize this potential in Web applications, browsers must expose rich new graphics APIs to Web content. The Mozilla project will meet this challenge with two major new features to be delivered in Firefox 1.5: integrated SVG and a new canvas HTML element. Work is also underway "under the hood" on a new unified graphics architecture that uses 3D graphics processors to accelerate all rendering. This work provides additional benefits to Web developers such as the ability to apply SVG effects to HTML content. Questions and Discussion Rich Web: SVG And Canvas In Mozilla - Discussion ...
CanvasGradient - Web APIs
The CanvasGradient interface represents an opaque object describing a gradient. It is returned by the methods CanvasRenderingContext2D.createLinearGradient() or CanvasRenderingContext2D.createRadialGradient(). It can be used as a fillStyle or strokeStyle. Properties As an opaque object, there is no exposed property. Methods There is no inherited method. CanvasGradient.addColorStop() Adds a new stop, defined by an offset and a color, to the gradient. If the offset is not between 0 and 1, inclusive, an INDEX_SIZE_ERR is raised; if the color can't be parsed as a CSS <color>, a SYNTAX_ERR is raised. Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasGradient' in that specification. Living Standard ...
CanvasRenderingContext2D.clearHitRegions() - Web APIs
The CanvasRenderingContext2D method clearHitRegions() removes all hit regions from the canvas. Syntax void ctx.clearHitRegions(); Examples Using the clearHitRegions method This example demonstrates the clearHitRegions() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Set some hit regions ctx.addHitRegion({id: 'eyes'}); ctx.addHitRegion({id: 'nose'}); ctx.addHitRegion({id: 'mouth'}); // Remove them altogether from the canvas ctx.clearHitRegions(); Specifications Canvas hit regions have been removed from the WHATWG Living Standard, although discussions about future standardization are ongoing. See https://github.com/whatwg/html/issues/3407 for more information. ...
CanvasRenderingContext2D.drawWidgetAsOnScreen() - Web APIs
Unlike drawWindow(), this API uses the operating system to snapshot the widget on-screen, rather than reading from Gecko's own compositor. This API cannot be used by Web content. It is only supported on Windows, only on widgets that use OMTC, and only from within the chrome process. Syntax void ctx.drawWidgetAsOnScreen(window); Parameters window The Window to render. Specifications Not part of any current specification or draft. ...
CanvasRenderingContext2D.measureText() - Web APIs
The CanvasRenderingContext2D.measureText() method returns a TextMetrics object that contains information about the measured text (such as its width, for example). Syntax ctx.measureText(text); Parameters text The text String to measure. Return value A TextMetrics object. Example Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a TextMetrics object using the following code: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let text = ctx.measureText('Hello world'); console.log(text.width); // 56; Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.measureText' in that specification. Living Standard ...
CanvasRenderingContext2D.removeHitRegion() - Web APIs
The CanvasRenderingContext2D method removeHitRegion() removes a given hit region from the canvas. Syntax void ctx.removeHitRegion(id); Parameters id A DOMString representing the id of the region that is to be removed. Examples Using the removeHitRegion method This example demonstrates the removeHitRegion() method. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); // Set a hit region ctx.addHitRegion({id: 'eyes'}); // Remove it from the canvas ctx.removeHitRegion('eyes'); Specifications Canvas hit regions have been removed from the WHATWG Living Standard, although discussions about future standardization are ongoing. See https://github.com/whatwg/html/issues/3407 for more informatio...
HTMLCanvasElement.transferControlToOffscreen() - Web APIs
The HTMLCanvasElement.transferControlToOffscreen() method transfers control to an OffscreenCanvas object, either on the main thread or on a worker. Syntax OffscreenCanvas HTMLCanvasElement.transferControlToOffscreen() Return value An OffscreenCanvas object. Examples var htmlCanvas = document.createElement('canvas'); var offscreen = htmlCanvas.transferControlToOffscreen(); var gl = offscreen.getContext('webgl'); // ... some drawing using the gl context ... // Push frames back to the original HTMLCanvasElement gl.commit(); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLCanvasElement.transferControlToOffscreen()' in that specification. Living Standard ...
HTMLCanvasElement: webglcontextlost event - Web APIs
ost event of the WebGL API is fired if the user agent detects that the drawing buffer associated with a WebGLRenderingContext object has been lost. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost event: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // "webglcontextlost" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextlost' in that specification. Rec...
HTMLCanvasElement: webglcontextrestored event - Web APIs
ere created before the context was lost are no longer valid. You need to reinitialize the state of your WebGL application and recreate resources. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); // "webglcontextrestored" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextrestored' in that spec...
OffscreenCanvas() - Web APIs
The OffscreenCanvas() constructor returns a newly instantiated OffscreenCanvas object. Syntax new OffscreenCanvas(width, height); Parameters width The width of the offscreen canvas. height The height of the offscreen canvas. Examples This example creates a new offscreen canvas using the OffscreenCanvas() constructor. We then initialize a WebGL context on it using the getContext() method. let offscreen = new OffscreenCanvas(256, 256); let gl = offscreen.getContext('webgl'); Specifications Specification Status Comment HTML Living StandardThe definition of 'OffscreenCanvas()' in that specification. Living Standard ...
OffscreenCanvas.height - Web APIs
The height property returns and sets the height of an OffscreenCanvas object. Syntax var pxl = offscreen.height; offscreen.height = pxl; Examples Creating a new offscreen canvas and returning or setting the height of the offscreen canvas: var offscreen = new OffscreenCanvas(256, 256); offscreen.height; // 256 offscreen.height = 512; Specifications Specification Status Comment HTML Living StandardThe definition of 'OffscreenCanvas.height' in that specification. Living Standard ...
OffscreenCanvas.transferToImageBitmap() - Web APIs
The OffscreenCanvas.transferToImageBitmap() method creates an ImageBitmap object from the most recently rendered image of the OffscreenCanvas. Syntax ImageBitmap OffscreenCanvas.transferToImageBitmap() Return value An ImageBitmap. Examples var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... offscreen.transferToImageBitmap(); // ImageBitmap { width: 256, height: 256 } Specifications Specification Status Comment HTML Living StandardThe definition of 'OffscreenCanvas.transferToImageBitmap()' in that specification. Living Standard ...
OffscreenCanvas.width - Web APIs
The width property returns and sets the width of an OffscreenCanvas object. Syntax var pxl = offscreen.width; offscreen.width = pxl; Examples Creating a new offscreen canvas and returning or setting the width of the offscreen canvas: var offscreen = new OffscreenCanvas(256, 256); offscreen.width; // 256 offscreen.width = 512; Specifications Specification Status Comment HTML Living StandardThe definition of 'OffscreenCanvas.width' in that specification. Living Standard ...
Index - Web APIs
Web › API › Index
ject Model (CSSOM) which aims at superseding it. 397 CSS Painting API API, CSS, CSS Paint API, Houdini, Painting, Reference The CSS Painting API -- part of the CSS Houdini umbrella of APIs -- allows developers to write JavaScript functions that can draw directly into an element's background, border, or content. 398 Using the CSS Painting API CSS, CSS Paint API, Canvas, Houdini, Learn The CSS Paint API is designed to enable developers to programmatically define images which can then be used anywhere a CSS image can be invoked, such as CSS background-image, border-image, mask-image, etc. 399 CSS Properties and Values API Houdini The CSS Properties and Values API -- part of the CSS Houdini umbrella of APIs -- allows developers to explic...
...ey for a stored Response. This method returns a Promise for a Response, or undefined if no match is found. 515 CacheStorage.open() API, CacheStorage, Experimental, Method, Reference, Service Workers, Service worker API, ServiceWorker, open The open() method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName. ...
...onse. This method returns a Promise for a Response, or undefined if no match is found. 515 CacheStorage.open() API, CacheStorage, Experimental, Method, Reference, Service Workers, Service worker API, ServiceWorker, open The open() method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName. ...
...And 165 more matches
Drawing graphics - Learn web development
Previous Overview: Client-side web APIs Next The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (SVG) language, to APIs for drawing on HTML <canvas> elements, (see The Canvas API and WebGL). This article provides an introduction to canvas, and further resources to allow you to learn more. Prerequisites: JavaScript basics (see first steps, building blocks, JavaScript objects), the basics of Client-side APIs Objective: To learn the basics of drawing on <canvas> elements using JavaScript. Graphics on the Web As we talked about in our HTML Multimedia and embedding module, the Web was originally just text, which was very boring, so images were introduced -- first via the <img> element and later via CS...
...ulate) SVG vector images -- as they are represented by markup -- there was still no way to do the same for bitmap images, and the tools available were rather limited. The Web still had no way to effectively create animations, games, 3D scenes, and other requirements commonly handled by lower level languages such as C++ or Java. The situation started to improve when browsers began to support the <canvas> element and associated Canvas API -- Apple invented it in around 2004, and other browsers followed by implementing it in the years that followed. As you'll see below, canvas provides many useful tools for creating 2D animations, games, data visualizations, and other types of app, especially when combined with some of the other APIs the web platform provides. The below example shows a simple 2D ...
...> element and associated Canvas API -- Apple invented it in around 2004, and other browsers followed by implementing it in the years that followed. As you'll see below, canvas provides many useful tools for creating 2D animations, games, data visualizations, and other types of app, especially when combined with some of the other APIs the web platform provides. The below example shows a simple 2D canvas-based bouncing balls animation that we originally met in our Introducing JavaScript objects module: Around 2006-2007, Mozilla started work on an experimental 3D canvas implementation. This became WebGL, which gained traction among browser vendors, and was standardized around 2009-2010. WebGL allows you to create real 3D graphics inside your web browser; the below example shows a simple rotatin...
...And 64 more matches
Applying styles and colors - Web APIs
You will learn how to add different colors, line styles, gradients, patterns and shadows to your drawings. Colors Up until now we have only seen methods of the drawing context. If we want to apply colors to a shape, there are two important properties we can use: fillStyle and strokeStyle. fillStyle = color Sets the style used when filling shapes. strokeStyle = color Sets the style for shapes' outlines. ...
...happening here. We use the two variables i and j to generate a unique RGB color for each square, and only modify the red and green values. The blue channel has a fixed value. By modifying the channels, you can generate all kinds of palettes. By increasing the steps, you can achieve something that looks like the color palettes Photoshop uses. ...
...eve something that looks like the color palettes Photoshop uses. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ', ' + Math.floor(255 - 42.5 * j) + ', 0)'; ctx.fillRect(j * 25, i * 25, 25, 25); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); The result looks like this: ScreenshotLive sample A strokeStyle example This example is similar to the one above, but uses the strokeStyle property to change the colors of the shapes' outlines. ...
...And 58 more matches
Advanced animations - Web APIs
<< PreviousNext >> In the last chapter we made some basic animations and got to know ways to get things moving. In this part we will have a closer look at the motion itself and are going to add some physics to make our animations more advanced. Drawing a ball We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up. ...
...eviousNext >> In the last chapter we made some basic animations and got to know ways to get things moving. In this part we will have a closer look at the motion itself and are going to add some physics to make our animations more advanced. Drawing a ball We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up. ...
... >> In the last chapter we made some basic animations and got to know ways to get things moving. In this part we will have a closer look at the motion itself and are going to add some physics to make our animations more advanced. Drawing a ball We are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. The following code will set us up. ...
...And 45 more matches
Index - Game development
and spheres using the Three.js library. It is assumed that before reading this you have read our 3D collision detection introductory article first, and have basic knowledge about Three.js. 15 3D games on the Web Games, Graphics, NeedsContent, NeedsExample, WebGL, WebVR, three.js For rich gaming experiences on the web, the weapon of choice is WebGL, which is rendered on HTML <canvas>. WebGL is basically an OpenGL ES 2.0 for the Web -- it's a JavaScript API providing tools to build rich interactive animations and of course, also games. You can generate and render dynamic 3D graphics with JavaScript that is hardware accelerated. 16 Building up a basic demo with A-Frame 3D, A-Frame, VR, Virtual Reality, Web, WebGL The WebXR and WebGL APIs already enable us ...
...opular 3D game engines used by developers. As with any other 3D library it provides built-in functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. 18 Building up a basic demo with PlayCanvas 3D, Animation, Beginner, Canvas, Games, PlayCanvas, Tutorial, WebGL, camera, lighting, rendering Of course, it depends on your approach -- designers may favor the online editor while programmers will prefer having the full control over the coding environment and will probably use the engine's source files. The good thing is that you have a choice and can pick whatever tools suit you bes...
...nvas, Tutorial, WebGL, camera, lighting, rendering Of course, it depends on your approach -- designers may favor the online editor while programmers will prefer having the full control over the coding environment and will probably use the engine's source files. The good thing is that you have a choice and can pick whatever tools suit you best. ...
...And 39 more matches
Using images - Web APIs
<< PreviousNext >> Until now we have created our own shapes and applied styles to them. One of the more exciting features of <canvas> is the ability to use images. These can be used to do dynamic photo compositing or as backdrops of graphs, for sprites in games, and so forth. External images can be used in any format supported by the browser, such as PNG, GIF, or JPEG. You can even use the image produced by other canvas elements on the same page as the source! Importing images into a canvas is basically a two step process: Get a reference to an HTMLImageElement object or to another canvas element as a source. It is also possible to use images by providing a URL. Draw the image on the canvas using the drawImage() function. Let's take a look at how to do this. Getting i...
... SVGImageElement These are images embedded using the <image> element. HTMLVideoElement Using an HTML <video> element as your image source grabs the current frame from the video and uses it as an image. ...
... The canvas API is able to use any of the following data types as an image source: HTMLImageElement These are images created using the Image() constructor, as well as any <img> element. SVGImageElement These are images embedded using the <image> element. HTMLVideoElement Using an HTML <video> element as your image source grabs the current frame from the video and uses it as an image. HTMLCanvasElement You can use another <canvas> element as your image source. These sources are collectively referred to by the type CanvasImageSource. There are several ways to get images for use on a canvas. Using images from the same page We can obtain a reference to images on the same page as the canvas by using one of: The document.images collection The document.getElementsByTagName() method ...
...And 26 more matches
Transformations - Web APIs
Canvas states are stored on a stack. ...
... Canvas states are stored on a stack. ...
... Canvas states are stored on a stack. Every time the save() method is called, the current drawing state is pushed onto the stack. A drawing state consists of The transformations that have been applied (i.e. translate, rotate and scale - see below). ...
...And 22 more matches
Basic animations - Web APIs
<< PreviousNext >> Since we're using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations. In this chapter we will take a look at how to do some basic animations. Probably the biggest limitation is, that once a shape gets drawn, it stays that way. If we need to move it we have to redraw it and everything that was drawn before it. It takes a lot of time to redraw complex frames and the performance depends highly on the speed of the computer it's running on. Basic animation steps These are the steps you need to take to draw a frame: Clear the canvas Unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. The easiest way to do this is...
...e performance depends highly on the speed of the computer it's running on. Basic animation steps These are the steps you need to take to draw a frame: Clear the canvas Unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. The easiest way to do this is using the clearRect() method. Save the canvas state If you're changing any setting (such as styles, transformations, etc.) which affect the canvas state and you want to make sure the original state is used each time a frame is drawn, you need to save that original state. Draw animated shapes The step where you do the actual frame rendering. Restore the canvas state If you've saved the state, restore it before drawing a new frame. Cont...
...For instance, it isn't possible to do an animation from within a for loop. That means we need a way to execute our drawing functions over a period of time. ...
...And 20 more matches
Compositing example - Web APIs
This sample program demonstrates a number of compositing operations. The output looks like this: Compositing example This code sets up the global values used by the rest of the program. ...
... This sample program demonstrates a number of compositing operations. The output looks like this: Compositing example This code sets up the global values used by the rest of the program. ...
... This sample program demonstrates a number of compositing operations. The output looks like this: Compositing example This code sets up the global values used by the rest of the program. ...
...And 19 more matches
Pointer Lock API - Web APIs
view This section provides a brief description of each property and method related to the pointer lock specification. requestPointerLock() The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock(). ...
...n provides a brief description of each property and method related to the pointer lock specification. requestPointerLock() The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock(). ...
...on of each property and method related to the pointer lock specification. requestPointerLock() The Pointer lock API, similar to the Fullscreen API, extends DOM elements by adding a new method, requestPointerLock(). As it has recently unprefixed, you would currently declare it something like this, for example if you wanted to request pointer lock on a canvas element: canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock; canvas.requestPointerLock() If a user has exited pointer lock via the default unlock gesture, or pointer lock has not previously been entered for this document, an event generated as a result of an engagement gesture must be received by the document before requestPointerLock will succeed. (from https://w3c.github.
...And 18 more matches
Taking still photos with WebRTC - Web APIs
ontains two components: a <video> element, which will receive the stream from WebRTC, and a <button> the user clicks to capture a video frame. <div class="camera"> <video id="video">Video stream not available.</video> <button id="startbutton">Take photo</button> </div> This is straightforward, and we'll see how it ties together when we get into the JavaScript code. Next, we have a <canvas> element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file. This canvas is kept hidden by styling the canvas with display:none, to avoid cluttering up the screen -- the user does not need to see this intermediate stage. We also have an <img> element into which we will draw the image -- this is the final display shown to t...
...The rest is just some page layout fluff and a bit of text offering a link back to this page. ...
...The rest is just some page layout fluff and a bit of text offering a link back to this page. ...
...And 17 more matches
WebGLRenderingContext - Web APIs
The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. ...
...The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. ...
...The WebGL tutorial has more information, examples, and resources on how to get started with WebGL. ...
...And 16 more matches
Using IIR filters - Web APIs
vices and graphic equalizers, and the filter response parameters can be specified, so that it can be tuned as needed. This article looks at how to implement one, and use it in a simple example. Demo Our simple example for this guide provides a play/pause button that starts and pauses audio play, and a toggle that turns an IIR filter on and off, altering the tone of the sound. It also provides a canvas on which is drawn the frequency response of the audio, so you can see what effect the IIR filter has. You can check out the full demo here on Codepen. Also see the source code on GitHub. It includes some different coefficient values for different lowpass frequencies -- you can change the value of the filterNumber constant to a value between 0 and 3 to check out the different available effects.
...could go for a linear approach, but it's far better when working with frequencies to take a log approach, so let's fill our array with frequency values that get larger further on in the array items. Now let's get our response data: iirFilter.getFrequencyResponse(myFrequencyArray, magResponseOutput, phaseResponseOutput); We can use this data to draw a filter frequency plot. ...
...h, but it's far better when working with frequencies to take a log approach, so let's fill our array with frequency values that get larger further on in the array items. Now let's get our response data: iirFilter.getFrequencyResponse(myFrequencyArray, magResponseOutput, phaseResponseOutput); We can use this data to draw a filter frequency plot. We'll do so on a 2d canvas context. ...
...And 14 more matches
Drawing text - Web APIs
<< PreviousNext >> After having seen how to apply styles and colors in the previous chapter, we will now have a look at how to draw text onto the canvas. Drawing text The canvas rendering context provides two methods to render text: fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position. Optionally with a maximum width to draw. strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. ...
...s to render text: fillText(text, x, y [, maxWidth]) Fills a given text at the given (x,y) position. Optionally with a maximum width to draw. strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. ...
...tion. Optionally with a maximum width to draw. strokeText(text, x, y [, maxWidth]) Strokes a given text at the given (x,y) position. Optionally with a maximum width to draw. A fillText example The text is filled using the current fillStyle. ...
...And 13 more matches
Color picker tool - CSS: Cascading Style Sheets
lock"> <div class="ui-color-picker" data-topic="picker" data-mode="HSL"></div> <div id="picker-samples" sample-id="master"></div> <div id="controls"> <div id="delete"> <div id="trash-can"></div> </div> <div id="void-sample" class="icon"></div> </div> </div> <div id="canvas" data-tutorial="drop"> <div id="zindex" class="ui-input-slider" data-topic="z-index" data-info="z-index" data-max="20" data-sensivity="10"></div> </div> </div> CSS /* * COLOR PICKER TOOL */ .ui-color-picker { width: 420px; margin: 0; border: 1px solid #DDD; background-color: #FFF; display: table; -moz-user-select: none; -webkit-user-select: n...
...k:hover { /*background-image: url('images/unlocked-hover.png');*/ background-position: bottom left; } #color-palette .controls .lock[locked-state='true'] { /*background-image: url('images/locked.png');*/ background-position: top left ; } #color-palette .controls .lock[locked-state='true']:hover { /*background-image: url('images/lock-hover.png');*/ background-position: top right; } /** * Canvas */ #canvas { width: 100%; height: 300px; min-height: 250px; border-top: 1px solid #DDD; background-image: url('https://mdn.mozillademos.org/files/6025/grain.png'); background-repeat: repeat; position: relative; float: left; } #canvas[data-tutorial='drop'] { text-align: center; font-size: 30px; color: #777; } #canvas[data-tutorial='drop']:before { content: "Drop colors here to comp...
...vas[data-tutorial='drop']:before { content: "Drop colors here to compare"; width: 40%; padding: 30px 9% 70px 11%; background-image: url('https://mdn.mozillademos.org/files/6075/drop.png'); background-repeat: no-repeat; background-position: left 35px top 60%; text-align: right; border: 3px dashed rgb(221, 221, 221); border-radius: 15px; position: absolute; top: 50px; left: 20%; } #canvas[data-tutorial='drop']:after { content: "adjust, change or modify"; width: 40%; font-size: 24px; position: absolute; top: 130px; left: 32%; z-index: 2; } #canvas [data-tutorial='dblclick'] { background-color: #999 !important; } #canvas [data-tutorial='dblclick']:before { content: "double click to activate"; width: 80px; color: #FFF; position: absolute; top: 10%; left: 20%; z-index...
...And 13 more matches
Cubic Bezier Generator - CSS: Cascading Style Sheets
<html> <canvas id="bezier" width="336" height="336"> </canvas> <form> <label for="x1">x1 = </label><input onchange="updateCanvas();" type="text" maxlength=6 id="x1" value="0.79" class='field'> <label for="y1">y1 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="y1" value="0.33" class='field'> <label for="x2">x2 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">Log</output> </form> </html> .field { width: 40px; } function updateCanvas() { var x1 = d...
...var y1 = document.getElementById('y1').value; var x2 = document.getElementById('x2').value; var y2 = document.getElementById('y2').value; drawBezierCurve(x1, y1, x2, y2); } const radius = 4; // Place needed to draw the rulers const rulers = 30.5; const margin = 10.5; const basic_scale_size = 5; // Size of 0.1 tick on the rulers var scaling; //LIMITATION: scaling is computed once: if canvas.height/canvas.width change it won't be recalculated var dragSM = 0; // Drag state machine: 0 = nodrag, others = object being dragged function initCanvas() { // get the canvas element using the DOM var canvas = document.getElementById('bezier'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawi...
...change it won't be recalculated var dragSM = 0; // Drag state machine: 0 = nodrag, others = object being dragged function initCanvas() { // get the canvas element using the DOM var canvas = document.getElementById('bezier'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); scaling = Math.min(canvas.height - rulers - margin, canvas.width - rulers - margin); canvas.onmousedown = mouseDown; canvas.onmouseup = mouseUp; } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } function cX(x) { return x * scaling + rulers; } function reverseX(x) { return (x - rulers) / scaling; } functi...
...And 13 more matches
Hit regions and accessibility - Web APIs
<< PreviousNext >> The <canvas> element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools like semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guidelines can help to make it more accessible. Fallback content The content inside the <canvas> ... </canvas> tags can be used as a fallback for browsers which don't support canvas rendering. It's also very useful for assistive technology users (like screen readers) which can read and interpret the sub DOM in it. A good example at html5accessibility.com demonstrates how this can be done: <canvas> <h2>Shapes</h2> <p>A rectangle with a black border. In the background is a pink circle.
...nblur="drawPicture();">circle</a>. ...
...;">triangle</a>, both of which are semi-opaque, so the full circle can be seen underneath.</p> </canvas> See the video how NVDA reads this example by Steve Faulkner. ARIA rules Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications more accessible to people with disabilities. You can use ARIA attributes to describe the behavior and purpose of the canvas element. See ARIA and ARIA techniques for more information. <canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas> Hit regions Whether the mouse coordinates are within a particular area on the canvas, is a common problem to solve. ...
...And 11 more matches
JavaScript modules - JavaScript
rt No support No supportSee implementation notes.See implementation notes.User must explicitly enable this feature.User must explicitly enable this feature. Introducing an example To demonstrate usage of modules, we've created a simple set of examples that you can find on GitHub. These examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas. These are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly. Note: If you want to download the examples and run them locally, you'll need to run them through a local web server. Basic example structure In our first example (see basic-modules) we have a file...
...ation about) different shapes on the canvas. These are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly. Note: If you want to download the examples and run them locally, you'll need to run them through a local web server. Basic example structure In our first example (see basic-modules) we have a file structure as follows: index.html main.js modules/ canvas.js square.js Note: All of the examples in this guide have basically the same structure; the above should start getting pretty familiar. ...
...ou'll need to run them through a local web server. Basic example structure In our first example (see basic-modules) we have a file structure as follows: index.html main.js modules/ canvas.js square.js Note: All of the examples in this guide have basically the same structure; the above should start getting pretty familiar. The modules directory's two modules are described below: canvas.js -- contains functions related to setting up the canvas: create() -- creates a canvas with a specified width and height inside a wrapper <div> with a specified ID, which is itself appended inside a specified parent element. Returns an object containing the canvas's 2D context and the wrapper's ID. createReportList() -- creates an unordered list appended inside a specified wrapper elem...
...And 11 more matches
Object building practice - Learn web development
nd object-oriented techniques in a real world context. Let's bounce some balls In this article we will write a classic "bouncing balls" demo, to show you how useful objects can be in JavaScript. Our little balls will bounce around on the screen, and change color when they touch each other. The finished example will look a little something like this: This example will make use of the Canvas API for drawing the balls to the screen, and the requestAnimationFrame API for animating the whole display -- you don't need to have any previous knowledge of these APIs, and we hope that by the time you've finished this article you'll be interested in exploring them more. Along the way we'll make use of some nifty objects, and show you a couple of nice techniques like bouncing balls off walls, a...
...'ll make use of some nifty objects, and show you a couple of nice techniques like bouncing balls off walls, and checking whether they have hit each other (otherwise known as collision detection). Getting started To begin with, make local copies of our index.html, style.css, and main.js files. These contain the following, respectively: A very simple HTML document featuring an <h1> element, a <canvas> element to draw our balls on, and elements to apply our CSS and JavaScript to our HTML. Some very simple styles, which mainly serve to style and position the <h1>, and get rid of any scrollbars or margin around the edge of the page (so that it looks nice and neat). Some JavaScript that serves to set up the <canvas> element and provide a general function that we're going to use. The first par...
...ements to apply our CSS and JavaScript to our HTML. Some very simple styles, which mainly serve to style and position the <h1>, and get rid of any scrollbars or margin around the edge of the page (so that it looks nice and neat). Some JavaScript that serves to set up the <canvas> element and provide a general function that we're going to use. The first part of the script looks like so: const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); const width = canvas.width = window.innerWidth; const height = canvas.height = window.innerHeight; This script gets a reference to the <canvas> element, then calls the getContext() method on it to give us a context on which we can start to draw. The resulting constant (ctx) is the object that directly represents the drawi...
...And 10 more matches
Visualizations with Web Audio API - Web APIs
ew Uint8Array(bufferLength); To actually retrieve the data and copy it into our array, we then call the data collection method we want, with the array passed as it's argument. For example: analyser.getByteTimeDomainData(dataArray); We now have the audio data for that moment in time captured in our array, and can proceed to visualize it however we like, for example by plotting it onto an HTML5 <canvas>. Let's go on to look at some specific examples. Creating a waveform/oscilloscope To create the oscilloscope visualisation (hat tip to Soledad Penades for the original code in Voice-change-O-matic), we first follow the standard pattern described in the previous section to set up the buffer: analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(...
...cific examples. ...
...(hat tip to Soledad Penades for the original code in Voice-change-O-matic), we first follow the standard pattern described in the previous section to set up the buffer: analyser.fftSize = 2048; var bufferLength = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); Next, we clear the canvas of what had been drawn on it before to get ready for the new visualization display: canvasCtx.clearRect(0, 0, WIDTH, HEIGHT); We now define the draw() function: function draw() { In here, we use requestAnimationFrame() to keep looping the drawing function once it has been started: var drawVisual = requestAnimationFrame(draw); Next, we grab the time domain data and copy it into our array analyser.getByteTimeDomainData(dataArray); Next, fill the canvas with a solid colour to start...
...And 10 more matches
TextMetrics - Web APIs
Properties TextMetrics.width Read only Is a double giving the calculated width of a segment of inline text in CSS pixels. It takes into account the current font of the context. TextMetrics.actualBoundingBoxLeft Read only Is a double giving the distance from the alignment point given by the CanvasRenderingContext2D.textAlign property to the left side of the bounding rectangle of the given text, in CSS pixels. The distance is measured parallel to the baseline. ...
... a textMetrics() instance can be retrieved using the CanvasRenderingContext2D.measureText() method. Properties TextMetrics.width Read only Is a double giving the calculated width of a segment of inline text in CSS pixels. It takes into account the current font of the context. TextMetrics.actualBoundingBoxLeft Read only Is a double giving the distance from the alignment point given by the CanvasRenderingContext2D.textAlign property to the left side of the bounding rectangle of the given text, in CSS pixels. The distance is measured parallel to the baseline. ...
...trics.actualBoundingBoxLeft Read only Is a double giving the distance from the alignment point given by the CanvasRenderingContext2D.textAlign property to the left side of the bounding rectangle of the given text, in CSS pixels. The distance is measured parallel to the baseline. TextMetrics.actualBoundingBoxRight Read only Is a double giving the distance from the alignment point given by the CanvasRenderingContext2D.textAlign property to the right side of the bounding rectangle of the given text, in CSS pixels. The distance is measured parallel to the baseline. ...
...And 9 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
mmersive presentation requires multiple renders of the scene--once from the perspective of each eye. When rendering the left eye, the XRWebGLLayer has its viewport configured to restrict drawing to the left half of the drawing surface. Contrarily, when rendering the right eye, the viewport is set to restrict drawing to the right half of the surface. This example demonstrates this by showing the canvas on the screen, even when presenting a scene as an immersive display using an XR device. Dependencies While we will not rely upon any 3D graphics frameworks such as three.js or the like for this example, we do use the glMatrix library for matrix math, which we've used in other examples in the past. This example also imports the WebXR polyfill maintained by the Immersive Web Working Group, which ...
...ing the GLSL code for the vertex and fragment shaders, and attaching the WebGL layer to the WebXR session before kicking off the rendering loop. It gets called as the handler for the promise returned by isSessionSupported(). ...
...and fragment shaders, and attaching the WebGL layer to the WebXR session before kicking off the rendering loop. It gets called as the handler for the promise returned by isSessionSupported(). ...
...And 9 more matches
Drag Operations - Web APIs
he user's pointer during the drag. This image is created automatically, so you do not need to create it yourself. However, you can use setDragImage() to specify a custom drag feedback image. event.dataTransfer.setDragImage(image, xOffset, yOffset); Three arguments are necessary. The first is a reference to an image. This reference will typically be to an <img> element, but it can also be to a <canvas> or any other element. The feedback image will be generated from whatever the image looks like on screen, although for images, they will be drawn at their original size. The second and third arguments to the setDragImage() method are offsets where the image should appear relative to the mouse pointer. It is also possible to use images and canvases that are not in a document. This technique is us...
... be generated from whatever the image looks like on screen, although for images, they will be drawn at their original size. The second and third arguments to the setDragImage() method are offsets where the image should appear relative to the mouse pointer. It is also possible to use images and canvases that are not in a document. ...
...e drawn at their original size. The second and third arguments to the setDragImage() method are offsets where the image should appear relative to the mouse pointer. It is also possible to use images and canvases that are not in a document. ...
...And 7 more matches
ImageData.data - Web APIs
Web › API › ImageData › data
ll, making 10,000 pixels in all. The data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all. let imageData = new ImageData(100, 100); console.log(imageData.data); // Uint8ClampedArray[40000] console.log(imageData.data.length); // 40000 Filling a blank ImageData object This example creates and fills a new ImageData object with colorful pixels. ...
...10,000 pixels in all. The data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all. let imageData = new ImageData(100, 100); console.log(imageData.data); // Uint8ClampedArray[40000] console.log(imageData.data.length); // 40000 Filling a blank ImageData object This example creates and fills a new ImageData object with colorful pixels. ...
...els in all. The data array stores four values for each pixel, making 4 x 10,000, or 40,000 values in all. let imageData = new ImageData(100, 100); console.log(imageData.data); // Uint8ClampedArray[40000] console.log(imageData.data.length); // 40000 Filling a blank ImageData object This example creates and fills a new ImageData object with colorful pixels. ...
...And 7 more matches
Clearing by clicking - Web APIs
<< PreviousNext >> This example demonstrates how to combine user interaction with WebGL graphics operations by clearing the rendering context with a random color when the user clicks. Clearing the rendering context with random colors This example provides a simple illustration of how to combine WebGL and user interaction. ...
... << PreviousNext >> This example demonstrates how to combine user interaction with WebGL graphics operations by clearing the rendering context with a random color when the user clicks. Clearing the rendering context with random colors This example provides a simple illustration of how to combine WebGL and user interaction. ...
...mple provides a simple illustration of how to combine WebGL and user interaction. Every time the user clicks the canvas or the button, the canvas is cleared with a new randomly chosen color. Note how we embed the WebGL function calls inside the event handler function. ...
...And 7 more matches
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
. Most operating systems have programs that can make calls, like Skype or FaceTime. Websites can make phone calls with registerProtocolHandler, such as web.skype.com. Other behaviors include saving the number to contacts, or sending the number to another device. See RFC 3966 for syntax, additional features, and other details about the tel: URL scheme. ...
...e programs that can make calls, like Skype or FaceTime. Websites can make phone calls with registerProtocolHandler, such as web.skype.com. Other behaviors include saving the number to contacts, or sending the number to another device. See RFC 3966 for syntax, additional features, and other details about the tel: URL scheme. ...
...sterProtocolHandler, such as web.skype.com. Other behaviors include saving the number to contacts, or sending the number to another device. See RFC 3966 for syntax, additional features, and other details about the tel: URL scheme. Using the download attribute to save a <canvas> as a PNG To save a <canvas> element's contents as an image, you can create a link with a download attribute and the canvas data as a data: URL: Example painting app with save link HTML <p>Paint by holding down the mouse button and moving it. ...
...And 7 more matches
Crisp pixel art look with image-rendering - Game development
The concept Retro pixel art aesthetics are getting popular, especially in indie games or game jam entries. But since today's screens render content at high resolutions, there is a problem with making sure the pixel art does not look blurry. Developers have been manually scaling up graphics so they are shown with blocks that represent pixels. Two downsides to this method are larger file sizes and compression artifacts. ...
...also allows you to use the images in their original, smaller size, thus saving download time. Also, some game techniques require algorithms that analyse images, which also benefit from working with smaller images. The CSS property to achieve this scaling is image-rendering. It is still experimental, but there is partial support in most browsers. ...
...h smaller images. The CSS property to achieve this scaling is image-rendering. It is still experimental, but there is partial support in most browsers. The steps to achieve this effect are: Create a <canvas> element and set its width and height attributes to the original, smaller resolution. Set its CSS width and height properties to be 2x or 4x the value of the HTML width and height. If the canvas was created with a 128 pixel width, for example, we would set the CSS width to 512px if we wanted a 4x scale. Set the <canvas> element's image-rendering CSS property to some value that does not make the image blurry. Either crisp-edges or pixelated will work. Check out the image-rendering article for more information on the differences between these values, and which prefixes to use depending on...
...And 6 more matches
Move the ball - Game development
You already know how to draw a ball from working through the previous article, so now let's make it move. Technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement -- just like how movement works with the movies. ...
...n2.html. You already know how to draw a ball from working through the previous article, so now let's make it move. Technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement -- just like how movement works with the movies. Defining a drawing loop To keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. You can run a function over and over again using a JavaScript timing function such as setInterval() or requestAnimationFrame(). Delete all the JavaScript you currently have inside your HTML file except for the first two ...
...c(50, 50, 10, 0, Math.PI*2); ctx.fillStyle = "#0095DD"; ctx.fill(); ctx.closePath(); Try your updated code now -- the ball should be repainted on every frame. Making it move You won't notice the ball being repainted constantly at the moment, as it's not moving. Let's change that. First, instead of a hardcoded position at (50,50) we will define a starting point at the bottom center part of the Canvas in variables called x and y, then use those to define the position the circle is drawn at. First, add the following two lines above your draw() function, to define x and y: var x = canvas.width/2; var y = canvas.height-30; Next update the draw() function to use the x and y variables in the arc() method, as shown in the following highlighted line: function draw() { ctx.beginPath(); ct...
...And 6 more matches
2D maze game with device orientation - Game development
s. The Phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to complete the game, so you can focus on the game idea itself. Starting with the project You can see Cyber Orb source code on GitHub. The folder structure is quite straightforward: the starting point is the index.html file where we initialize the framework and set up an <canvas> to render the game on. You can open the index file in your favourite browser to launch the game and try it. There are also three folders in the directory: img: All the images that we will use in the game. src: The JavaScript files with all the source code of the game defined inside. audio: The sound files used in the game. Setting up the Canvas We will be rendering our game on Canvas,...
...gin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/Boot.js"></script> <script src="src/Preloader.js"></script> <script src="src/MainMenu.js"></script> <script src="src/Howto.js"></script> <script src="src/Game.js"></script> </head> <body> <script> (function() { var game = new Phaser.Game(320, 480, Phaser.CANVAS, 'game'); game.state.add('Boot', Ball.Boot); game.state.add('Preloader', Ball.Preloader); game.state.add('MainMenu', Ball.MainMenu); game.state.add('Howto', Ball.Howto); game.state.add('Game', Ball.Game); game.state.start('Boot'); })(); </script> </body> </html> So far we have a simple HTML website with some basic content in the <head> section: charset, title, CSS styling...
... game.state.add('Game', Ball.Game); game.state.start('Boot'); })(); </script> </body> </html> So far we have a simple HTML website with some basic content in the <head> section: charset, title, CSS styling and the inclusion of the JavaScript files. The <body> contains initialization of the Phaser framework and the definitions of the game states. var game = new Phaser.Game(320, 480, Phaser.CANVAS, 'game'); The line above will initialize the Phaser instance -- the arguments are the width of the Canvas, height of the Canvas, rendering method (we're using CANVAS, but there are also WEBGL and AUTO options available) and the optional ID of the DOM container we want to put the Canvas in. If there's nothing specified in that last argument or the element is not found, the Canvas will be added to...
...And 6 more matches
Using Pointer Events - Web APIs
This example is based on the one in the touch events overview, except it uses the pointer events input event model. Another difference is that because pointer events are pointer device agnostic, the application accepts coordinate-based inputs from a mouse, a pen, or a fingertip using the same code. This application will only work on a browser that supports pointer events. A live version of this application is available on GitHub. The source code is available on Github and pull requests and bug reports are welcome. Definitions Surface A touch-sensitive surface. ...
...oint A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger), stylus, mouse, or any other method for specifying a single point on the surface. Example The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus, mouse, or other method of pointing at a location. ...
... or any other method for specifying a single point on the surface. Example The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus, mouse, or other method of pointing at a location. Create a canvas The touch-action property is set to none to prevent the browser from applying its default touch behavior to the application. <canvas id="canvas" width="600" height="600" style="border:solid black 1px; touch-action:none"> Your browser does not support canvas element. ...
...And 6 more matches
WebGLRenderingContext.getContextAttributes() - Web APIs
The WebGLRenderingContext.getContextAttributes() method returns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. Syntax gl.getContextAttributes(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
... The WebGLRenderingContext.getContextAttributes() method returns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. Syntax gl.getContextAttributes(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
... The WebGLRenderingContext.getContextAttributes() method returns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. Syntax gl.getContextAttributes(); Return value A WebGLContextAttributes object that contains the actual context parameters, or null if the context is lost. ...
...And 6 more matches
A basic 2D WebGL animation example - Web APIs
That is, (0, 0) is at the top-left corner and the bottom-right corner is at (600, 460). Vertex shader First, let's take a look at the vertex shader. Its job, as always, is to convert the coordinates we're using for our scene into clipspace coordinates (that is, the system by which (0, 0) is at the center of the context and each axis extends from -1.0 to 1.0 regardless of the actual size of the context). ...
... precision highp float; #endif uniform vec4 uGlobalColor; void main() { gl_FragColor = uGlobalColor; } </script> This starts by specifying the precision of the float type, as required. Then we set the global gl_FragColor to the value of the uniform uGlobalColor, which is set by the JavaScript code to the color being used to draw the square. HTML The HTML consists solely of the <canvas> that we'll obtain a WebGL context on. <canvas id="glcanvas" width="600" height="460"> Oh no! Your browser doesn't support canvas! </canvas> JavaScript Globals and initialization First, the global variables. We won't discuss these here; instead, we'll talk about them as they're used in the code to come. let gl = null; let glCanvas = null; // Aspect ratio and coordinate system // details ...
...rtexNumComponents; let vertexCount; // Rendering data shared with the // scalers. ...
...And 6 more matches
Hello vertex attributes - Web APIs
<< PreviousNext >> This WebGL example demonstrates how to combine shader programming and user interaction by sending user input to the shader using vertex attributes. Hello World program in GLSL How to send input to a shader program by saving data in GPU memory. <p>First encounter with attributes and sending data to GPU. ...
...t >> This WebGL example demonstrates how to combine shader programming and user interaction by sending user input to the shader using vertex attributes. Hello World program in GLSL How to send input to a shader program by saving data in GPU memory. <p>First encounter with attributes and sending data to GPU. ...
...e shader programming and user interaction by sending user input to the shader using vertex attributes. Hello World program in GLSL How to send input to a shader program by saving data in GPU memory. <p>First encounter with attributes and sending data to GPU. ...
...And 6 more matches
Simple color animation - Web APIs
basic user interaction of starting and stopping the animation. The timer and the timer handler function establish the animation loop, a set of drawing commands that are executed at a regular period (typically, every frame; in this case, once per second). ...
...interaction of starting and stopping the animation. The timer and the timer handler function establish the animation loop, a set of drawing commands that are executed at a regular period (typically, every frame; in this case, once per second). ...
... and the timer handler function establish the animation loop, a set of drawing commands that are executed at a regular period (typically, every frame; in this case, once per second). ...
...And 6 more matches
Getting started with WebGL - Web APIs
WebGL programs consist of control code written in JavaScript and shader code (GLSL) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background. This article will introduce you to the basics of using WebGL. ...
... be found in the webgl-examples GitHub repository. It's worth noting here that this series of articles introduces WebGL itself; however, there are a number of frameworks available that encapsulate WebGL's capabilities, making it easier to build 3D applications and games, such as THREE.js and BABYLON.js. Preparing to render in 3D The first thing you need in order to use WebGL for rendering is a canvas. ...
...sitory. It's worth noting here that this series of articles introduces WebGL itself; however, there are a number of frameworks available that encapsulate WebGL's capabilities, making it easier to build 3D applications and games, such as THREE.js and BABYLON.js. Preparing to render in 3D The first thing you need in order to use WebGL for rendering is a canvas. The HTML fragment below declares a canvas that our sample will draw into. ...
...And 6 more matches
Audio and video manipulation - Developer guides
The beauty of the web is that you can combine technologies to create new forms. Having native audio and video in the browser means we can use these data streams with technologies such as <canvas>, WebGL or Web Audio API to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. This article provides a reference to explain what you need to do. Video manipulation The ability to read the pixel values from each frame of a video can be very useful. Video and canvas The <canvas> element provides a surface for drawing graphics onto web pages; it is very powerful and can be coupled tightly with video. The general technique is to: Write a frame from the <video> element to an intermediary <canvas> element. Read the da...
... Pause and repeat. For example, let's process a video to display it in greyscale. In this case, we'll show both the source video and the output greyscale frames. ...
...be very useful. Video and canvas The <canvas> element provides a surface for drawing graphics onto web pages; it is very powerful and can be coupled tightly with video. The general technique is to: Write a frame from the <video> element to an intermediary <canvas> element. Read the data from the intermediary <canvas> element and manipulate it. Write the manipulated data to your "display" <canvas>. Pause and repeat. For example, let's process a video to display it in greyscale. In this case, we'll show both the source video and the output greyscale frames. ...
...And 6 more matches
Bounce off the walls - Game development
Simple collision detection To detect the collision we will check whether the ball is touching (colliding with) the wall, and if so, we will change the direction of its movement accordingly. ...
... Simple collision detection To detect the collision we will check whether the ball is touching (colliding with) the wall, and if so, we will change the direction of its movement accordingly. ...
...ode, somewhere below the existing variable declarations: var ballRadius = 10; Now update the line that draws the ball inside the drawBall() function to this: ctx.arc(x, y, ballRadius, 0, Math.PI*2); Bouncing off the top and bottom There are four walls to bounce the ball off -- let's focus on the top one first. We need to check, on every frame, whether the ball is touching the top edge of the Canvas -- if yes, we'll reverse the ball movement so it will start to move in the opposite direction and stay within the visible boundaries. Remembering that the coordinate system starts from the top left, we can come up with something like this: if(y + dy < 0) { dy = -dy; } If the y value of the ball position is lower than zero, change the direction of the movement on the y axis by setting it equ...
...And 5 more matches
A basic ray-caster - Web APIs
This article provides an interesting real-world example of using the <canvas> element to do software rendering of a 3D environment using ray-casting. Open in new window Why? After realizing, to my delight, that the nifty <canvas> element I'd been reading about was not only soon to be supported in Firefox, but was already supported in the current version of Safari, I had to try a little experiment. The canvas overview and tutorial I found here at MDN are great, but nobody had written about animation yet, so I thought I'd try a port of a basic raycaster I'd worked on a while ago, and see what sort of performance we can expect from a JavaScript-controlled pixel buffer. How? The basic idea is to use setInterval() at some arbitrary delay that corresponds to a desired frame rate. After ever...
...re at MDN are great, but nobody had written about animation yet, so I thought I'd try a port of a basic raycaster I'd worked on a while ago, and see what sort of performance we can expect from a JavaScript-controlled pixel buffer. How? The basic idea is to use setInterval() at some arbitrary delay that corresponds to a desired frame rate. ...
...c raycaster I'd worked on a while ago, and see what sort of performance we can expect from a JavaScript-controlled pixel buffer. How? The basic idea is to use setInterval() at some arbitrary delay that corresponds to a desired frame rate. After every interval an update function will repaint the canvas showing the current view. I know I could have started with a simpler example, but I'm sure the canvas tutorial will get to that, and I wanted to see if I could do this. So every update, the raycaster looks to see if you've pressed any keys lately, to conserve calculations by not casting if you're idle. If you have, then the canvas is cleared, the ground and sky are drawn, the camera position and/or orientation are updated, and the rays are cast out. As the rays intersect walls, then they render ...
...And 5 more matches
Compositing and clipping - Web APIs
most situations, but it limits the order in which composite shapes are built. We can, however, change this behaviour by setting the globalCompositeOperation property. In addition, the clip property allows us to hide unwanted parts of shapes. ...
...he canvas (not limited to rectangles like the clearRect() method does) and more. globalCompositeOperation = type This sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use. See compositing examples for the code of the following examples. Clipping paths A clipping path is like a normal canvas shape but it acts as a mask to hide unwanted parts of shapes. This is visualized in the image on the right. The red star shape is our clipping path. Everything that falls outside of this path won't get drawn on the canvas. If we compare clipping paths to the globalCompositeOperation property we've seen above, we see two compositing modes that achieve more or less the same effect in source-in and...
...This makes clipping paths ideal for drawing multiple shapes in a restricted area. In the chapter about drawing shapes I only mentioned the stroke() and fill() methods, but there's a third method we can use with paths, called clip(). ...
...And 5 more matches
Document.mozSetImageElement() - Web APIs
nd image using the -moz-element CSS function. imageElement is the new element to use as the background corresponding to that image element string. Specify null to remove the background element. Example This example changes the background of a <div> block each time the block is clicked by the user. View this example live. ...
...e This example changes the background of a <div> block each time the block is clicked by the user. View this example live. <style type="text/css"> #mybox { background-image: -moz-element(#canvasbg); text-align: center; width: 400px; height: 400px; cursor: pointer; } </style> The CSS defined by the <style> block above is used by our <div> to use an element with the id "canvasbg" as its background. ...
...lock is clicked by the user. View this example live. <style type="text/css"> #mybox { background-image: -moz-element(#canvasbg); text-align: center; width: 400px; height: 400px; cursor: pointer; } </style> The CSS defined by the <style> block above is used by our <div> to use an element with the id "canvasbg" as its background. ...
...And 5 more matches
MouseEvent.region - Web APIs
Web › API › MouseEvent › region
The MouseEvent.region read-only property returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. Example Example of using the event.region combined with CanvasRenderingContext2D.addHitRegion() method. ...
... The MouseEvent.region read-only property returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. Example Example of using the event.region combined with CanvasRenderingContext2D.addHitRegion() method. ...
... The MouseEvent.region read-only property returns the id of the canvas hit region affected by the event. If no hit region is affected, null is returned. Syntax var hitRegion = instanceOfMouseEvent.region Return value A DOMString representing the id of the hit region. Example Example of using the event.region combined with CanvasRenderingContext2D.addHitRegion() method. ...
...And 5 more matches
Touch events - Web APIs
Represents an event that occurs when the state of touches on the surface changes. Touch Represents a single point of contact between the user and the touch surface. TouchList Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time. Example This example tracks multiple touchpoints at a time, allowing the user to draw in a <canvas> with more than one finger at a time. It will only work on a browser that supports touch events. Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. ...
...with more than one finger at a time. It will only work on a browser that supports touch events. Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. ...
...her contact method. Create a canvas <canvas id="canvas" width="600" height="600" style="border:solid black 1px;"> Your browser does not support canvas element. </canvas> <br> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> Setting up the event handlers When the page loads, the startup() function shown below will be called. ...
...And 5 more matches
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
abled = false; }, 2000); } Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a <button> across page loads. Use the autocomplete attribute to control this feature. Validation Buttons don't participate in constraint validation; they have no real value to be constrained. Examples The below example shows a very simple drawing app created using a <canvas> element and some simple CSS and JavaScript (we'll hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas. <div class="toolbar"> <input type="color" aria-label="select pen color"> <input type="range" min="2" max="50" value="30" aria-label="select pen size"><span class="outp...
...l hide the CSS for brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas. ...
... brevity). The top two controls allow you to choose the color and size of the drawing pen. The button, when clicked, invokes a function that clears the canvas. ...
...And 5 more matches
nsIDOMWindowUtils
.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) Implemented by: Window. ...
...uced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) Implemented by: Window. ...
... Inherits from: nsISupports Last changed in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) Implemented by: Window. ...
...And 4 more matches
AnalyserNode.getFloatTimeDomainData() - Web APIs
rameters array The Float32Array that the time domain data will be copied to. If the array has fewer elements than the AnalyserNode.frequencyBinCount, excess elements are dropped. If it has more elements than needed, excess elements are ignored. Return value None. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 1024; var bufferLength...
...udio input. For more complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... ...
...new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... ...
...And 4 more matches
AnalyserNode - Web APIs
AnalyserNode.getByteTimeDomainData() Copies the current waveform, or time-domain, data into a Uint8Array (unsigned byte array) passed into it. Examples Note: See the guide Visualizations with Web Audio API for more information on creating audio visualizations. Basic usage The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... analyser.fftSize = 2048; var buff...
...mples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... ...
...nge-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... ...
...And 4 more matches
ImageData() - Web APIs
ng a blank ImageData object This example creates an ImageData object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels. let imageData = new ImageData(200, 100); // ImageData { width: 200, height: 100, data: Uint8ClampedArray[80000] } Initializing ImageData with an array This example instantiates an ImageData object with pixel colors defined by an array. ...
...ImageData object This example creates an ImageData object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels. let imageData = new ImageData(200, 100); // ImageData { width: 200, height: 100, data: Uint8ClampedArray[80000] } Initializing ImageData with an array This example instantiates an ImageData object with pixel colors defined by an array. ...
...object This example creates an ImageData object that is 200 pixels wide and 100 pixels tall, containing a total of 20,000 pixels. let imageData = new ImageData(200, 100); // ImageData { width: 200, height: 100, data: Uint8ClampedArray[80000] } Initializing ImageData with an array This example instantiates an ImageData object with pixel colors defined by an array. ...
...And 4 more matches
Boilerplate 1 - Web APIs
ering context By now you are quite used to seeing the same pieces of HTML, CSS, and JavaScript repeated again and again. So we are going to hide them from now on. This would allow us to focus on the interesting pieces of code that are most relevant for learning WebGL. Specifically, the HTML has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. The CSS contains rules for body, canvas, and button. Any additional non-trivial CSS and HTML will be displayed on the pages of specific examples. In following examples, we will use a JavaScript helper function, getRenderingContext(), to initialize the WebGL rendering context. By now, you should be able to understand what the function does. Basically, it gets ...
...In case of error, it displays an error message and returns null. Finally, all JavaScript code will run within an immediate function, which is a common JavaScript technique (see Function). The function declaration and invocation will also be hidden. ...
...ack, and returns the initialized context. In case of error, it displays an error message and returns null. Finally, all JavaScript code will run within an immediate function, which is a common JavaScript technique (see Function). The function declaration and invocation will also be hidden. HTML <p>[ Some descriptive text about the example. ]</p> <button>[ Optional button element. ...
...And 4 more matches
Clearing with colors - Web APIs
In addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. ...
... In addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. ...
... which in turn changes how input (in this case, a clear command) translates into output (in this case, all pixels are set to green). Finally, we note that color in WebGL is usually in RGBA format, that is four numerical components for red, green, blue and alpha (opacity). Therefore, clearColor() takes four arguments. ...
...And 4 more matches
Raining rectangles - Web APIs
ases of the WebGL graphics pipeline and state machine. In addition, the example demonstrates how to integrate the WebGL function calls within a game loop. The game loop is responsible for drawing the animation frames, and keeping the animation responsive to user input. Here, the game loop is implemented using timeouts. <p>You caught <strong>0</strong>. ...
... In addition, the example demonstrates how to integrate the WebGL function calls within a game loop. The game loop is responsible for drawing the animation frames, and keeping the animation responsive to user input. Here, the game loop is implemented using timeouts. <p>You caught <strong>0</strong>. ...
...ion, the example demonstrates how to integrate the WebGL function calls within a game loop. The game loop is responsible for drawing the animation frames, and keeping the animation responsive to user input. Here, the game loop is implemented using timeouts. <p>You caught <strong>0</strong>. ...
...And 4 more matches
WebGL model view projection - Web APIs
of the larger Z values. WebGLBox example This example will create a custom WebGLBox object that will draw a 2D box on the screen. Note: The code for each WebGLBox example is available in this github repo and is organized by section. In addition there is a JSFiddle link at the bottom of each section. ...
...x example This example will create a custom WebGLBox object that will draw a 2D box on the screen. Note: The code for each WebGLBox example is available in this github repo and is organized by section. In addition there is a JSFiddle link at the bottom of each section. ...
...e a custom WebGLBox object that will draw a 2D box on the screen. Note: The code for each WebGLBox example is available in this github repo and is organized by section. In addition there is a JSFiddle link at the bottom of each section. ...
...And 4 more matches
Visualizing an audio spectrum - Archive of obsolete content
This example calculates and displays Fast Fourier Transform (FFT) spectrum data for the playing audio. The function handling the loadedMetaData event stores the metadata of the audio element in global variables; the function for the MozAudioAvailable event does an FFT of the samples and displays them in a canvas. NOTE: You can use the AudioNode called AnalyserNode to perform real-time FFT analysis on an audio stream, rather than the code shown below. ...
...hem in a canvas. NOTE: You can use the AudioNode called AnalyserNode to perform real-time FFT analysis on an audio stream, rather than the code shown below. ...
...udioNode called AnalyserNode to perform real-time FFT analysis on an audio stream, rather than the code shown below. ...
...And 3 more matches
Displaying a graphic with audio samples - Archive of obsolete content
les from an audio stream and display them behind an image (in this case, the Mozilla logo), giving the impression that the image is built from the samples. ...
...ehind an image (in this case, the Mozilla logo), giving the impression that the image is built from the samples. ...
...mples. ...
...And 3 more matches
2D collision detection - Game development
// collision detected! } Rect code <div id="cr-stage"></div> <p>Move the rectangle with arrow keys. ...
...Move the rectangle with arrow keys. ...
... Circle Collision Another simple shape for collision detection is between two circles. This algorithm works by taking the centre points of the two circles and ensuring the distance between the centre points are less than the two radii added together. Playable code <div id="cr-stage"></div> <p>Move the circle with arrow keys. Green means collision, blue means no collisi...
...And 3 more matches
3D games on the Web - Game development
WebGL is basically an OpenGL ES 2.0 for the Web -- it's a JavaScript API providing tools to build rich interactive animations and of course, also games. You can generate and render dynamic 3D graphics with JavaScript that is hardware accelerated. Documentation and browser support The WebGL project documentation and specification is maintained by the Khronos Group, not the W3C as with most of the web APIs. Support on modern browsers is very good, even on mobile, so you don't have to worry about that too much. ...
...working on. Using a framework for 3D games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself. The most popular JavaScript 3D library is Three.js, a multi-purpose tool that makes common 3D techniques simpler to implement. There are other popular game development libraries and frameworks worth checking too; A-Frame, PlayCanvas and Babylon.js are among the most recognizable ones with rich documentation, online editors and active communities. Building up a basic demo with A-Frame A-Frame is a web framework for building 3D and VR experiences. Under the hood, it is a Three.js framework with a declarative entity-component pattern, meaning we can build scenes with just HTML. See the Building up a basic demo with A-Frame su...
...r 3D game engines used by developers. As with any other 3D library, it provides built-in functions to help you implement common 3D functionality more quickly. See the Building up a basic demo with Babylon.js subpage for the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. Building up a basic demo with PlayCanvas PlayCanvas is a popular 3D WebGL game engine open-sourced on GitHub, with an editor available online and good documentation. See the Building up a basic demo with PlayCanvas subpage for higher-level details, and further articles showing how to create demos using the PlayCanvas library, and the online editor. Building up a basic demo with Three.js Three.js, like any other library, gives you a h...
...And 3 more matches
Finishing up - Game development
There's always room for improvements in any game we write. For example, we can offer more than one life to the player. They could make a mistake or two and still be able to finish the game. We could also improve our code rendering. Giving the player some lives Implementing lives is quite straightforward. ...
...We can also reset the ball and the paddle positions when the player begins with their next life. So, in the draw() function replace the following three lines: alert("GAME OVER"); document.location.reload(); clearInterval(interval); // Needed for Chrome to end game ...
...If there are no lives left, the game is lost; if there are still some lives left, then the position of the ball and the paddle are reset, along with the movement of the ball. Rendering...
...And 3 more matches
Mouse controls - Game development
The game itself is actually finished, so let's work on polishing it up. We have already added keyboard controls, but we could easily add mouse controls too. Listening for mouse movement Listening for mouse movement is even easier than listening for key presses: all we need is the listener for the mousemove event. ...
...the keyup event: document.addEventListener("mousemove", mouseMoveHandler, false); Anchoring the paddle movement to the mouse movement We can update the paddle position based on the pointer coordinates -- the following handler function will do exactly that. ...
..., mouseMoveHandler, false); Anchoring the paddle movement to the mouse movement We can update the paddle position based on the pointer coordinates -- the following handler function will do exactly that. Add the following function to your code, below the previous line you added: function mouseMoveHandler(e) { var relativeX = e.clientX - canvas.offsetLeft; if(relativeX > 0 && relativeX < canvas.width) { paddleX = relativeX - paddleWidth/2; } } In this function we first work out a relativeX value, which is equal to the horizontal mouse position in the viewport (e.clientX) minus the distance between the left edge of the canvas and left edge of the viewport (canvas.offsetLeft) -- effectively this is equal to the distance between the canvas left edge and the mouse pointer. If t...
...And 3 more matches
Paddle and keyboard controls - Game development
The ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no interactivity. It's not a game if you cannot control it! So let's add some user interaction: a controllable paddle. Defining a paddle to hit the ball So, we need a paddle to hit the ball. Let's define a few variables for that. ...
... but currently there's no interactivity. It's not a game if you cannot control it! So let's add some user interaction: a controllable paddle. Defining a paddle to hit the ball So, we need a paddle to hit the ball. Let's define a few variables for that. ...
...It's time to implement some keyboard controls. ...
...And 3 more matches
AnalyserNode.fftSize - Web APIs
be a power of 2 between 252^5 and 2152^15, so one of: 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, and 32768. Defaults to 2048. Note: If its value is not a power of 2, or it is outside the specified range, a DOMException with the name IndexSizeError is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 2048; var buff...
...ntext)(); var analyser = audioCtx.createAnalyser(); ... ...
...; ... ...
...And 3 more matches
FileReader.readAsBinaryString() - Web APIs
dend is triggered. At that time, the result attribute contains the raw binary data from the file. Note that this method was once removed from the File API specification, but re-introduced for backward compatibility. Using FileReader.readAsArrayBuffer() is recommended. Syntax instanceOfFileReader.readAsBinaryString(blob); Parameters blob The Blob or File from which to read. ...
...the result attribute contains the raw binary data from the file. Note that this method was once removed from the File API specification, but re-introduced for backward compatibility. Using FileReader.readAsArrayBuffer() is recommended. Syntax instanceOfFileReader.readAsBinaryString(blob); Parameters blob The Blob or File from which to read. ...
...ta from the file. Note that this method was once removed from the File API specification, but re-introduced for backward compatibility. Using FileReader.readAsArrayBuffer() is recommended. Syntax instanceOfFileReader.readAsBinaryString(blob); Parameters blob The Blob or File from which to read. ...
...And 3 more matches
Basic scissoring - Web APIs
this case). This again demonstrates the typical order of commands in WebGL. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline. ...
...of commands in WebGL. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline. ...
...ds in WebGL. We first tweak WebGL state. In this case, enabling the scissor test and establishing a rectangular mask. Only when the WebGL state has been satisfactorily tweaked, we execute the drawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline. ...
...And 3 more matches
Color masking - Web APIs
<< PreviousNext >> This WebGL example modifies random colors by applying color masking to limit the range of displayed colors to specific shades. Masking random colors This example modifies the random color animation by applying color masking with colorMask(). You can think of the color masking operation as if looking at the colored canvas through some tinted glass or color filter. So, by masking off the blue and green channels, you are only allowing the red component of pixels to be updated, and therefore it is as if you were looking through a red tinted glass. Color masking allows us to demonstrate some basics of color theory. By masking off some channel(s), we are in fact biasing the displayed colors towards the complementary color. So, clearly masking both blue and red, wou...
... a certain order, where the output of each operation serves as the input of the next. So, for example, clearing operation sets the value of each pixel to the chosen clear color. Masking occurs later in the pipeline, and modifies the pixel color value, so the final result on the screen is that of the clear color, tinted by the color mask. ...
...rves as the input of the next. So, for example, clearing operation sets the value of each pixel to the chosen clear color. Masking occurs later in the pipeline, and modifies the pixel color value, so the final result on the screen is that of the clear color, tinted by the color mask. ...
...And 3 more matches
Hello GLSL - Web APIs
<< PreviousNext >> This WebGL example demonstrates a very basic GLSL shader program that draws a solid color square. Note: This example will most likely work in all modern desktop browsers. But it may not work in some mobile or older browsers. If the canvas remains blank, you can check the output of the next example, which draws exactly the same thing. But remember to read through the explanations and code on this page, before moving on to the next. Hello World program in GLSL A very simple first shader program. ...
...l modern desktop browsers. But it may not work in some mobile or older browsers. If the canvas remains blank, you can check the output of the next example, which draws exactly the same thing. But remember to read through the explanations and code on this page, before moving on to the next. Hello World program in GLSL A very simple first shader program. ...
...mobile or older browsers. If the canvas remains blank, you can check the output of the next example, which draws exactly the same thing. But remember to read through the explanations and code on this page, before moving on to the next. Hello World program in GLSL A very simple first shader program. ...
...And 3 more matches
self.createImageBitmap() - Web APIs
exists on the global scope in both windows and workers. It accepts a variety of different image sources, and returns a Promise which resolves to an ImageBitmap. Syntax const imageBitmapPromise = createImageBitmap(image[, options]); const imageBitmapPromise = createImageBitmap(image, sx, sy, sw, sh[, options]); Parameters image An image source, which can be an <img>, SVG <image>, <video>, <canvas>, HTMLImageElement, SVGImageElement, HTMLVideoElement, HTMLCanvasElement, Blob, ImageData, ImageBitmap, or OffscreenCanvas object. sx The x coordinate of the reference point of the rectangle from which the ImageBitmap will be extracted. sy The y coordinate of the reference point of the rectangle from which the ImageBitmap will be extracted. sw The width of the rectangle from which the Image...
...es the algorithm to be used for resizing the input to match the output dimensions. One of pixelated, low (default), medium, or high. Return value A Promise which resolves to an ImageBitmap object containing bitmap data from the given rectangle. Example Creating sprites from a sprite sheet This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. ...
... Return value A Promise which resolves to an ImageBitmap object containing bitmap data from the given rectangle. Example Creating sprites from a sprite sheet This example loads a sprite sheet, extracts individual sprites, and then renders each sprite to the canvas. A sprite sheet is an image containing multiple smaller images, each of which you want to be able to render separately. ...
...And 3 more matches
Performance fundamentals - Web Performance
loper's or user's perspective, this answers the question, "What does the platform do for you?" Web technologies The Web platform provides many tools, some better suited for particular jobs than others. All application logic is written in JavaScript. To display graphics, developers can use HTML or CSS (i.e. high-level declarative languages), or use low-level imperative interfaces offered by the <canvas> element (which includes WebGL). Somewhere "in between" HTML/CSS and Canvas is SVG, which offers some benefits of both. HTML and CSS greatly increase productivity, sometimes at the expense of framerate or pixel-level control over rendering. Text and images reflow automatically, UI elements automatically receive the system theme, and the system provides "built-in" support for some use cases devel...
... benefits of both. HTML and CSS greatly increase productivity, sometimes at the expense of framerate or pixel-level control over rendering. Text and images reflow automatically, UI elements automatically receive the system theme, and the system provides "built-in" support for some use cases developers may not think of initially, like different-resolution displays or right-to-left languages. ...
... Gecko rendering The Gecko JavaScript engine supports just-in-time (JIT) compilation. ...
...And 3 more matches
Index - Archive of obsolete content
on-modal notification and further interaction with users 173 Autocomplete Code snippets, Form Fill, Satchel No summary! 174 Bookmarks Code snippets, Developing Mozilla, Extensions, Places No summary! 175 Boxes Code snippets Make the BOX style="display: block" and the wrapping behavior will occur when the box is resized: 176 Canvas code snippets Canvas, Code snippets, Graphics No summary! 177 Cookies Add-ons, Code snippets, Cookies, Extensions No summary! 178 Customizing the download progress bar No summary! 179 Delayed Execution Code snippets No summary! 180 Dialogs and Prompts Add-ons, Code snippets, Extensions, XUL No summary! ...
...lements and lists. E4X also adds new JavaScript operators for filtering XML lists, and for enumerating XML children and descendants. Another E4X feature: the ability to bind a W3C DOM document to a new XML object, reflecting the DOM in E4X terms so that updates to either the DOM or the E4X object hierarchy show up in the other. 744 Rich Web No summary! 745 SVG And Canvas In Mozilla Presentations, SVG Today's Web browsers offer somewhat limited graphics capabilities to Web developers. Advances in hardware, especially graphics processors, offer the potential for far richer graphics in interactive applications. To realize this potential in Web applications, browsers must expose rich new graphics APIs to Web content. The Mozilla project will meet this chall...
...ics capabilities to Web developers. Advances in hardware, especially graphics processors, offer the potential for far richer graphics in interactive applications. To realize this potential in Web applications, browsers must expose rich new graphics APIs to Web content. The Mozilla project will meet this challenge with two major new features to be delivered in Firefox 1.5: integrated SVG and a new canvas HTML element. Work is also underway "under the hood" on a new unified graphics architecture that uses 3D graphics processors to accelerate all rendering. This work provides additional benefits to Web developers such as the ability to apply SVG effects to HTML content. 746 XUL - Mozilla's XML User Interface Language Presentations, XUL Ben Goodger, lead engineer for Mozilla Fir...
...And 2 more matches
Examples - Game development
vaScript, WebGL, and related technologies. The first two sections list playable games, while the second is a catch-all area to list demos that aren't necessarily interactive/games. Free/demo games Beloola WebVR platform to connect passionate people. Experience both available on 2D screens and on VR HMDs (Settings / Switch to VR mode). Tanx A multiplayer tank battle game, created with PlayCanvas. Hyper Vanguard Force A neat vertically scrolling space shooter. Swooop A plane flying game: control your plane and collect the jewels. Again, created with PlayCanvas. Save the Day Fly your rescue chopper around the disaster area and save the stranded victims (ga.me.) Polycraft A shipwreck 'n survive game. Explore the island and defeat the monsters. HexGL A fast-paced, futuristic racing...
...game. BananaBread A multiplayer, 3D first-person shooter game developed using Emscripten, WebGL, and WebRTC. Monster Madness A WebGL and asm.js-based multiplayer online shooter, developed by Nom Nom Games and Trendy entertainment. Auralux WebGL and asm.js-based strategy game: capture all the suns to win! BrowserQuest A MMORPG created by the Little Workshop and Mozilla. Shoot The Rocks A canvas 2D single-player shooter in the style of Atari's classic Asteroids arcade game from 1979. Star Citadel A new take on Star Castle, Cinematronics' classic 1980 arcade game, built with canvas 2D. Classic Platformer Canvas 2D game based on `Visual-ts game engine` - physics based on Matter.js Commercial games Oort Online A MMO exploration, building, and battle game (currently in developmen...
... Oort Online A MMO exploration, building, and battle game (currently in development.) A Wizard's Lizard Top down Zelda-esque exploration/RPG. QbQbQb A sci-fi themed arcade puzzle game. Bullet Force 3D multiplayer first-person shooter. Elliot Quest 8-bit graphic retro adventure game. RPG MO Isometric MMORPG with similarities to RuneScape Classic and Ultima. Katan.io HTML5 and canvas implementation of Settlers of Catan. Pyramid Solitaire Ancient Egypt Pyramid solitaire app ported to WebAssembly with Emscripten Assorted demos WaveGL WebGL visualizer for sound sources. Canvas Airport Simulation Animated map showing planes taking off and landing at airports, along with flight path patterns. Animation Physics 3D rendering of terrain and cars, using ammo.js for the p...
...And 2 more matches
Mobile touch controls - Game development
vaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's entirely up to you which approach you to choose. Pure JavaScript approach We could implement touch events on our own -- setting up event listeners and assigning relevant functions to them would be quite straightforward: var el = document.getElementsByTagName("canvas")[0]; el.addEventListener("touchstart", handleStart); el.addEventListener("touchmove", handleMove); el.addEventListener("touchend", handleEnd); el.addEventListener("touchcancel", handleCancel); This way, touching the game's <canvas> on the mobile screen would emit events, and thus we could manipulate the game in any way we want (for example, moving the space ship around). The events are as follo...
...We can get the first touch (e.touches[0], our example is not multitouch-en...
...We can get the first touch (e.touches[0], our example is not multitouch-enabled), extract the pageX and pageY variables and set the player's ship posi...
...And 2 more matches
Tiles and tilemaps overview - Game development
ue in 2D game development, consisting of building the game world or level map out of small, regular-shaped images called tiles. This results in performance and memory usage gains -- big image files containing entire level maps are not needed, as they are constructed by small images or image fragments multiple times. This set of articles covers the basics of creating tile maps using JavaScript and Canvas (although the same high level techniques could be used in any programming language.) Besides the performance gains, tilemaps can also be mapped to a logical grid, which can be used in other ways inside the game logic (for example creating a path-finding graph, or handling collisions) or to create a level editor. Some popular games that use this technique are Super Mario Bros, Pacman, Zelda: Lin...
...y 2000. Think about any game that uses regularly repeating squares of background, and you'll probably find it uses tilemaps. The tile atlas The most efficient way to store the tile images is in an atlas or spritesheet. This is simply all of the required tiles grouped together in a single image file. When it's time to draw a tile, only a small section of this bigger image is rendered on the game canvas. The below images shows a tile atlas of 8 x 4 tiles: Using an atlas also has the advantage of naturally assigning every tile an index. This index is perfect to use as the tile identifier when creating the tilemap object. The tilemap data structure It is common to group all the information needed to handle tilemaps into the same data structure or object. These data objects (map object example...
... below image shows an example of an atlas for an isometric tileset. Performance Drawing scrolling tile maps can take a toll on performance. Usually, some techniques need to be implemented so scrolling can be smooth. The first approach, as discussed above, is to only draw tiles that will be visible. But sometimes, this is not enough. One simple technique consists of pre-rendering the map in a canvas on its own (when using the Canvas API) or on a texture (when using WebGL), so tiles don't need to be re-drawn every frame and rendering can be done in just one blitting operation. Of course, if the map is large this doesn't really solve the problem -- and some systems don't have a very generous limit on how big a texture can be. One way consists of drawing the section that will be visible off-ca...
...And 2 more matches
Build the brick field - Game development
After modifying the gameplay mechanics, we are now able to lose -- this is great as it means the game is finally feeling more like a game. However, it will quickly get boring if all you do is bounce the ball off the walls and the paddle. ...
...var brickRowCount = 3; var brickColumnCount = 5; var brickWidth = 75; var brickHeight = 20; var brickPadding = 10; var brickOffsetTop = 30; var brickOffsetLeft = 30; Here we've defined the number of rows and columns of bricks , their width and height, the padding between the bricks so they won't touch each other and a top and left offset so they won't start being drawn right from the edge of the Canvas. We will hold all our bricks in a two-dimensional array. It will contain the brick columns (c), which in turn will contain the brick rows (r), which in turn will each contain an object containing the x and y position to paint each brick on the screen. Add the following just below your variables: var bricks = []; for(var c=0; c<brickColumnCount; c++) { bricks[c] = []; for(var r=0; r<bric...
...The problem is that we're painting them all in one place, at coordinates (0,0). What we need to do is include some calculations that will work out the x and y position of each brick for each loop iteration: var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft; var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop; Each bri...
...And 2 more matches
Game over - Game development
It's fun to watch the ball bouncing off the walls and be able to move the paddle around, but other than that the game does nothing and doesn't have any progression or end goal. It would be good from the gameplay point of view to be able to lose. The logic behind losing in breakout is simple. If you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. Implementing game over Let's try to implement game over in our game. ...
.... It would be good from the gameplay point of view to be able to lose. The logic behind losing in breakout is simple. If you miss the ball with the paddle and let it reach the bottom edge of the screen, then it's game over. Implementing game over Let's try to implement game over in our game. Here's the piece of code from the third lesson where we made the ball bounce off the walls: if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) { dx = -dx; } if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) { dy = -dy; } Instead of allowing the ball to bounce off all four walls, let's only allow three now -- left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the b...
...{ dx = -dx; } if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) { dy = -dy; } Instead of allowing the ball to bounce off all four walls, let's only allow three now -- left, top and right. Hitting the bottom wall will end the game. We'll edit the second if block so it's an if else block that will trigger our "game over" state upon the ball colliding with the bottom edge of the canvas. For now we'll keep it simple, showing an alert message and restarting the game by reloading the page. ...
...And 2 more matches
Scaling - Game development
We can make the game scale to fit on any screen size automatically during the preload stage, so we don't have to worry about it later. ...
... scale object There's a special scale object available in Phaser with a few handy methods and properties available. Update your existing preload() function as follows: function preload() { game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.pageAlignHorizontally = true; game.scale.pageAlignVertically = true; } scaleMode has a few different options available for how the Canvas can be scaled: NO_SCALE -- nothing is scaled. EXACT_FIT -- scale the canvas to fill all the available space both vertically and horizontally, without preserving the aspect ratio. SHOW_ALL -- scales the canvas, but keeps the aspect ratio untouched, so images won't be skewed like in the previous mode. There might be black stripes visible on the edges of the screen, but we can live with that. ...
...SCALE -- nothing is scaled. EXACT_FIT -- scale the canvas to fill all the available space both vertically and horizontally, without preserving the aspect ratio. SHOW_ALL -- scales the canvas, but keeps the aspect ratio untouched, so images won't be skewed like in the previous mode. There might be black stripes visible on the edges of the screen, but we can live with that. RESIZE -- creates the canvas with the same size as the available width and height, so you have to place the objects inside your game dynamically; this is more of an advanced mode. ...
...And 2 more matches
OS.File for the main thread
After image loads it then draws it to canvas, makes it a blob, and uses FileReader to turn it into ArrayBuffer(View), then uses OS.File.writeAtomic to save to disk. var img = new Image(); img.onload = fu...
...ize)); } outFile.close(); }).then( null, function onFailure(reason) { outFile.close(); throw reason; } ); } Example: Save Canvas to Disk This exmaple uses Image to load an image from a path (note: if your path is a file on disk you must use local file; this is accomplished with OS.Path.toFileURI, which accepts a string). ...
...ple uses Image to load an image from a path (note: if your path is a file on disk you must use local file; this is accomplished with OS.Path.toFileURI, which accepts a string). After image loads it then draws it to canvas, makes it a blob, and uses FileReader to turn it into ArrayBuffer(View), then uses OS.File.writeAtomic to save to disk. ...
...And 2 more matches
Animated PNG graphics
Mozilla › Tech › APNG
ative to MNG, providing a spec suitable for the most common usage of animated images on the Internet. APNG is backwards-compatible with PNG; any PNG decoder should be able to ignore the APNG-specific chunks and display a single image. Terminology The default image is the image described by the standard 'IDAT' chunks, and is the image that is displayed by decoders that do not support APNG. The canvas is the area on the output device on which the frames are to be displayed. The contents of the canvas are not necessarily available to the decoder. As per the PNG Specification, if a 'bKGD' chunk exists it may be used to fill the canvas if there is no preferrable background. The output buffer is a pixel array with dimensions specified by the width and height parameters of the PNG 'IHDR' chunk. Co...
... Fully transparent black means red, green, blue and alpha components are all set to zero. ...
... Fully transparent black means red, green, blue and alpha components are all set to zero. ...
...And 2 more matches
AnalyserNode.frequencyBinCount - Web APIs
FrequencyData() copy into the provided TypedArray. For technical reasons related to how the Fast Fourier transform is defined, it is always half the value of AnalyserNode.fftSize. Therefore, it will be one of 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, and 16384. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxD...
...ur Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... ...
...analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... ...
...And 2 more matches
AnalyserNode.getByteFrequencyData() - Web APIs
ata will be copied to. For any sample which is silent, the value is -Infinity. If the array has fewer elements than the AnalyserNode.frequencyBinCount, excess elements are dropped. If it has more elements than needed, excess elements are ignored. Return value None. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 256; var bufferLength = analyse...
... audio input. For more examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... ...
...indow.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); ... ...
...And 2 more matches
AnalyserNode.getByteTimeDomainData() - Web APIs
) Parameters array The Uint8Array that the time domain data will be copied to. If the array has fewer elements than the AnalyserNode.fftSize, excess elements are dropped. If it has more elements than needed, excess elements are ignored. Return value void | None Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); const analyser = audioCtx.createAnalyser(); ... analyser.fftSize = 2048; cons...
...window.webkitAudioContext)(); const analyser = audioCtx.createAnalyser(); ... ...
... audioCtx.createAnalyser(); ... ...
...And 2 more matches
AnalyserNode.maxDecibels - Web APIs
om getFloatFrequencyData() or getByteFrequencyData(), any frequencies with an amplitude of maxDecibels or higher will be returned as +1.0 or 255, respectively. Note: If a value less than or equal to AnalyserNode.minDecibels is set, an IndexSizeError exception is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxD...
...ur Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... ...
...analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... ...
...And 2 more matches
AnalyserNode.minDecibels - Web APIs
ing data from getFloatFrequencyData() or getByteFrequencyData(), any frequencies with an amplitude of minDecibels or lower will be returned as 0.0 or 0, respectively. Note: If a value greater than AnalyserNode.maxDecibels is set, an INDEX_SIZE_ERR exception is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxD...
...ur Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... ...
...analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; ... ...
...And 2 more matches
AnalyserNode.smoothingTimeConstant - Web APIs
quencyData/AnalyserNode.getByteFrequencyData calls. In technical terms, we apply a Blackman window and smooth the values over time. The default value is good enough for most cases. Note: If a value outside the range 0-1 is set, an INDEX_SIZE_ERR exception is thrown. Example The following example shows basic usage of an AudioContext to create an AnalyserNode, then requestAnimationFrame and <canvas> to collect frequency data repeatedly and draw a "winamp bargraph style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128-205 for relevant code). If you are curious about the effect the smoothingTimeConstant() has, try cloning the above example and setting analyser.smoothingTimeConstant = 0; instead. ...
...alue changes are much more jarring. var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); analyser.minDecibels = -90; analyser.maxDecibels = -10; analyser.smoothingTimeConstant = 0.85; ... ...
...nalyser.minDecibels = -90; analyser.maxDecibels = -10; analyser.smoothingTimeConstant = 0.85; ... ...
...And 2 more matches
BaseAudioContext.createAnalyser() - Web APIs
ontext)(); var analyser = audioCtx.createAnalyser(); ... ...
...); ... ...
...ngth = analyser.frequencyBinCount; var dataArray = new Uint8Array(bufferLength); analyser.getByteTimeDomainData(dataArray); // draw an oscilloscope of the current audio source function draw() { drawVisual = requestAnimationFrame(draw); analyser.getByteTimeDomainData(dataArray); canvasCtx.fillStyle = 'rgb(200, 200, 200)'; canvasCtx.fillRect(0, 0, WIDTH, HEIGHT); canvasCtx.lineWidth = 2; canvasCtx.strokeStyle = 'rgb(0, 0, 0)'; canvasCtx.beginPath(); var sliceWidth = WIDTH * 1.0 / bufferLength; var x = 0; for(var i = 0; i < bufferLength; i++) { var v = dataArray[i] / 128.0; var y = v * HEIGHT/2; if(i === 0) { canvasCtx.moveTo(x, y); } else { canvasCtx.lineTo(x, y); } ...
...And 2 more matches
Using the CSS Painting API - Web APIs
we employ the registerPaint() function to name our CSS Paint worklet. It takes two parameters. The first is the name we give the worklet -- this is the name we will use in our CSS as the parameter of the paint() function when we want to apply this styling to an element. ...
...nction when we want to apply this styling to an element. The second parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. registerPaint('headerHighlight', class { /* define if alphatransparency is allowed alpha is set to true by default. If set to false, all colours used on the canvas will be fully opaque */ static get contextOptions() { return { alpha: true }; } /* ctx is the 2D drawing context a subset of the HTML5 Canvas API. */ paint(ctx) { ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillRect(0, 15, 200, 20); /* order: x, y, w, h */ } }); In this class example we have defined a single context option ...
...ubset of the HTML5 Canvas API. */ paint(ctx) { ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillRect(0, 15, 200, 20); /* order: x, y, w, h */ } }); In this class example we have defined a single context option with the contextOptions() function: we returned a simple object stating alpha transparency is allowed. We have then used the paint() function to paint to our canvas. A paint() function can take three arguments. Here we have provided one argument: the rendering context (we'll look at more in due course), often refered to by the variable name ctx. The 2D Rendering Context is a subset of the HTML5 Canvas API; the version available to Houdini (called the PaintRenderingContext2D) is a further subset containing most of the features available in the full Canvas AP...
...And 2 more matches
The HTML DOM API - Web APIs
he HTML DOM API is made up of the interfaces that define the functionality of each of the elements in HTML, as well as any supporting types and interfaces they rely upon. The functional areas included in the HTML DOM API include: Access to and control of HTML elements via the DOM. Access to and manipulation of form data. Interacting with the contents of 2D images and the context of an HTML <canvas>, for example to draw on top of them. Management of media connected to the HTML media elements (<audio> and <video>). Dragging and dropping of content on webpages. Access to the browser navigation history Supporting and connective interfaces for other APIs such as Web Components, Web Storage, Web Workers, WebSocket, and Server-sent events. HTML DOM concepts and usage In this article, we'll...
...ly the functionality common to all HTML elements such as the element's ID, its coordinates, the HTML making up the element, information about scroll position, and so forth. In order to expand upon the functionality of the core HTMLElement interface to provide the features needed by a specific element, the HTMLElement class is subclassed to add the needed properties and methods. For example, the <canvas> element is represented by an object of type HTMLCanvasElement. HTMLCanvasElement augments the HTMLElement type by adding properties such as height and methods like getContext() to provide canvas-specific features. The overall inheritance for HTML element classes looks like this: As such, an element inherits the properties and methods of all of its ancestors. For example, consider a <a> eleme...
...tion, the HTML DOM API includes a few interfaces and types to support the HTML element interfaces. HTML element interfaces These interfaces represent specific HTML elements (or sets of related elements which have the same properties and methods associated with them). ...
...And 2 more matches
ImageCapture.grabFrame() - Web APIs
he live video in a MediaStreamTrack and returns a Promise that resolves with a ImageBitmap containing the snapshot. Syntax const bitmapPromise = imageCapture.grabFrame() Return value A Promise that resolves to an ImageBitmap object. Example This example is extracted from this Simple Image Capture demo. ...
...abFrame() Return value A Promise that resolves to an ImageBitmap object. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by grabFrame() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...se that resolves to an ImageBitmap object. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by grabFrame() to copy the returned frame to a <canvas> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...And 2 more matches
WebGLRenderingContext.makeXRCompatible() - Web APIs
</button> The first button starts the game, continuing to present the game onscreen as usual. The second button will be used to start the game in immersive-vr mode. Note the inclusion of a use-webxr class on the VR mode button. This is important, which we'll explore shortly. ...
...ame, continuing to present the game onscreen as usual. The second button will be used to start the game in immersive-vr mode. Note the inclusion of a use-webxr class on the VR mode button. This is important, which we'll explore shortly. ...
...the game onscreen as usual. The second button will be used to start the game in immersive-vr mode. Note the inclusion of a use-webxr class on the VR mode button. This is important, which we'll explore shortly. ...
...And 2 more matches
Scissor animation - Web APIs
square, we set its color once, and then update only its position every frame. The clear color state of WebGL remains at the set value, until we change it again when a new square is created. ...
... position every frame. The clear color state of WebGL remains at the set value, until we change it again when a new square is created. ...
... every frame. The clear color state of WebGL remains at the set value, until we change it again when a new square is created. ...
...And 2 more matches
Textures from code - Web APIs
<< PreviousNext >> This WebGL example provides a simple demonstration of procedural texturing with fragment shaders. That is, using code to generate textures for use in shading WebGL objects. Drawing textures with code Texturing a point sprite with calculations done per-pixel in the fragment shader. <p>Texture from code. ...
...es a simple demonstration of procedural texturing with fragment shaders. That is, using code to generate textures for use in shading WebGL objects. Drawing textures with code Texturing a point sprite with calculations done per-pixel in the fragment shader. <p>Texture from code. ...
...le demonstration of procedural texturing with fragment shaders. That is, using code to generate textures for use in shading WebGL objects. Drawing textures with code Texturing a point sprite with calculations done per-pixel in the fragment shader. <p>Texture from code. ...
...And 2 more matches
Adding 2D content to a WebGL context - Web APIs
ction is very simple. It uses a few utility routines we'll cover shortly. ...
...c(gl.LEQUAL); // Near things obscure far things // Clear the canvas before we start drawing on it. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Create a perspective matrix, a special matrix that is // used to simulate the distortion of perspective in a camera. // Our field of view is 45 degrees, with a width/height // ratio that matches the display size of the canvas // and we only want to see objects between 0.1 units // and 100 units away from the camera. ...
...a perspective matrix, a special matrix that is // used to simulate the distortion of perspective in a camera. // Our field of view is 45 degrees, with a width/height // ratio that matches the display size of the canvas // and we only want to see objects between 0.1 units // and 100 units away from the camera. const fieldOfView = 45 * Math.PI / 180; // in radians const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight; const zNear = 0.1; const zFar = 100.0; const projectionMatrix = mat4.create(); // note: glmatrix.js always has the first argument // as the destination to receive the result. mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar); // Set the drawing posit...
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
a minimum, so you can detect when the session is over. If you use XR input controllers, watch the inputsourceschange event to detect the addition or removal of XR input controllers, and the various select and squeeze action events. You may want to watch for the XRSystem event devicechange so you can be advised when the set of available immersive devices changes. Obtain a WebGL context for the canvas into which you intend to render your frames by calling the HTMLCanvasElement method getContext() on the target context. Set up your WebGL data and models and prepare to render the scene. Set the WebGL context as the source for the XR system by creating an XRWebGLLayer and passing set the value of the session's renderState property baseLayer. Perform calculations for the initial position and sc...
...g an XRWebGLLayer and passing set the value of the session's renderState property baseLayer. Perform calculations for the initial position and scale of your objects as needed. Begin the frame rendering cycle. ...
... the value of the session's renderState property baseLayer. Perform calculations for the initial position and scale of your objects as needed. Begin the frame rendering cycle. ...
...And 2 more matches
Window.screenLeft - Web APIs
Web › API › Window › screenLeft
Note: screenLeft is an alias of the older Window.screenX property. screenLeft was originally supported only in IE but was introduced everywhere due to popularity. Syntax leftWindowPos = window.screenLeft Returns A number equal to the number of CSS pixels from the left edge of the browser viewport to the left edge of the screen. ...
...ge of the browser viewport to the left edge of the screen. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...een. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...And 2 more matches
Window.screenTop - Web APIs
Web › API › Window › screenTop
reen. Note: screenTop is an alias of the older Window.screenY property. screenTop was originally supported only in IE but was introduced everywhere due to popularity. Syntax topWindowPos = window.screenTop Returns A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen. ...
...dge of the browser viewport to the top edge of the screen. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...een. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using screenLeft/screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...And 2 more matches
Window.screenX - Web APIs
Web › API › Window › screenX
ross modern browsers in more recent times -- Window.screenLeft. This was originally supported only in IE but was introduced everywhere due to popularity. Syntax leftWindowPos = window.screenX Returns A number equal to the number of CSS pixels from the left edge of the browser viewport to the left edge of the screen. ...
...o the left edge of the screen. Examples In our screenleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle. In this example we are using Window.screenLeft/Window.screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...nleft-screentop (source code) example, you'll see a canvas onto which has been drawn a circle. In this example we are using Window.screenLeft/Window.screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...And 2 more matches
Window.screenY - Web APIs
Web › API › Window › screenY
was implemented across modern browsers in more recent times -- Window.screenTop. This was originally supported only in IE but was introduced everywhere due to popularity. Syntax topWindowPos = window.screenY Returns A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen. ...
...wser viewport to the top edge of the screen. Examples In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using Window.screenLeft/Window.screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
... In our screenleft-screentop example, you'll see a canvas onto which has been drawn a circle. In this example we are using Window.screenLeft/Window.screenTop plus Window.requestAnimationFrame() to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ...
...And 2 more matches
Web media technologies
with visible controls for user-controlled playback of audio files. Accessible from JavaScript as HTMLAudioElement objects. <video> The <video> element is an endpoint for video content in a Web context. It can be used to simply present video files, or as a destination for streamed video content. <video> can also be used as a way to link media APIs with other HTML and DOM technologies, including <canvas> (for frame grabbing and manipulation), for example. Accessible from JavaScript as HTMLVideoElement objects. <track> The HTML <track> element can be placed within an <audio> or <video> element to provide a reference to a WebVTT format subtitle or caption track to be used when playing the media. Accessible from JavaScript as HTMLTrackElement objects. <source> The HTML <source> element is used ...
... Playing video in a 3D environment In this guide, we examine how to play video into a 3D scene. This technique can be used in both standard WebGL applications presented on a flat computer screen, or in a WebXR-generated virtual or augmented reality environment. Other topics Related topics which may be of interest, since they can be used in tandem with media APIs in interesting ways. ...
...n a 3D environment In this guide, we examine how to play video into a 3D scene. This technique can be used in both standard WebGL applications presented on a flat computer screen, or in a WebXR-generated virtual or augmented reality environment. Other topics Related topics which may be of interest, since they can be used in tandem with media APIs in interesting ways. ...
...And 2 more matches
XUL Questions and Answers - Archive of obsolete content
lements without IDs The original developers only tend to put IDs where they need them. As an extension author, you have at least two options: use DOM methods to dynamically create or rearrange elements file an enhancement request in Bugzilla to have extra IDs added. ...
... So how can I do this same way as <if...
... So how can I do this same way as <iframe>? You can't right now I want to create ...
... </template> </menupopup> </menulist> DrawWindow with transparent background possible? With Mozilla trunk --------------------------------------------------------- nsIDOMCanvasRenderingContext2D* c2d = //coming from <canvas> nsIDOMWindow* window = //coming from <iframe> c2d->DrawWindow( window, ..., "rgba(0,0,0,0)"); --------------------------------------------------------- This makes canvas background transparent if background is transparent but when "window" is coming from top level content window, background is not transparent. So how can I do this same way as <iframe>? You can't right now I want to create dynamically multiple elements with datasource attribute. I want to create XUL element in the javascript, assign datasources/ref/template attribute to it so that the content ...
MSX Emulator (jsMSX) - Archive of obsolete content
avaScript currently is mostly an interpreted language in web browsers, it is at least an order of magnitude slower than other languages such as C and Java. Therefore, jsMSX requires a very fast computer to emulate MSX at the normal 50-60 interrupts per second inside a web browser. Why? The initial motivation was to find some interesting project to develop while exploring the possibilities of the <canvas> tag and JavaScript language in the most recent web browsers like Firefox 2. As you may have realized, many challenges on performance are faced when developing in JavaScript. They present an interesting testbed for pushing the current JavaScript implementations to their limits and for comparing their relative speed. jsMSX can also be used to tightly integrate existing MSX programs in web page log...
... respectively. ...
...tively. ...
...le to read zip and lhz file streams is also necessary to load compressed rom files. ...
Building up a basic demo with Babylon.js - Game development
ement common 3D functionality more quickly. In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. We will try to create a simple demo first -- a cube rendered on the screen. If you have already worked through our Building up a basic demo series with Three.js, PlayCanvas or A-Frame (or you are familiar with other 3D libraries) you'll notice that Babylon.js works on similar concepts: camera, light and objects. Environment setup To start developing with Babylon.js, you don't need much. You should start off by: Making sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Creating a directory to store your experiment...
... Creating a directory to store your experiments in. Saving a copy of the latest Babylon.js engine inside your directory. Opening the Babylon.js documentation in a separate tab -- it is useful to refer to. ...
...ylon.js documentation in a separate tab -- it is useful to refer to. HTML structure Here's the HTML structure we will use: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>MDN Games: Babylon.js demo</title> <style> html,body,canvas { margin: 0; padding: 0; width: 100%; height: 100%; font-size: 0; } </style> </head> <body> <script src="babylon.js"></script> <canvas id="render-canvas"></canvas> <script> var canvas = document.getElementById("render-canvas"); /* all our JavaScript code goes here */ </script> </body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element (which Babylon.js will use to render the content on) to fill the entire available viewport space. The f...
...ion like the document <title>, and some CSS to set the width and height of the <canvas> element (which Babylon.js will use to render the content on) to fill the entire available viewport space. The first <script> element includes the Babylon.js library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the <canvas> element. Before reading on, copy this code to a new text file and save it in your working directory as index.html. Initialising the Babylon.js engine We have to create a Babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game. Add the following code to the bottom of your second <script> element: var engine = new BABYLON.Engine(canva...
Building up a basic demo with Three.js - Game development
development environment, structuring the necessary HTML, the fundamental objects of Three, and how to build up a basic demo. Note: We chose Three because it is one of the most popular WebGL libraries, and it is easy to get started with. We are not trying to say it is better than any other WebGL library available, and you should feel free to try another library, such as CopperLicht, GLGE, or PlayCanvas. Environment setup To start developing with Three.js, you don't need much. You should: Make sure you are using a modern browser with good WebGL support, such as the latest Firefox or Chrome. Create a directory to store your experiments in. Save a copy of the latest minimized Three.js library inside your directory. Open the Three.js documentation in a separate tab -- it is useful to refer...
...te a directory to store your experiments in. Save a copy of the latest minimized Three.js library inside your directory. Open the Three.js documentation in a separate tab -- it is useful to refer to. ...
...The first <script> element includes the Three.js library in the page, and we will write our example code inside the second. There are two helper variables already included, which store the window's width and height. ...
...example code inside the second. There are two helper variables already included, which store the window's width and height. Before reading further, copy this code to a new text file, and save it in your working directory as index.html. Renderer A renderer is a tool which displays scenes right in your browser. There are a few different renderers: WebGL is the default, and others you can use are Canvas, SVG, CSS, and DOM. They differ in how everything is rendered, so the WebGL implementation will implement differently than the CSS one. Despite the variety of ways they achieve the goal, the experience will look the same for the user. Thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. var renderer = new THREE.WebGLRenderer({antialias:true});...
2D breakout game using pure JavaScript - Game development
To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. ...
... To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. ...
...sms, and winning and losing states. To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial you should be able to build your own simple Web games. Lesson details All the lessons -- and the different versions of the MDN Breakout game we are building together -- are available on GitHub: Create the Canvas and draw on it Move the ball Bounce off the walls Paddle and keyboard controls Game over Build the brick field Collision detection Track the score and win Mouse controls Finishing up Starting with pure JavaScript is the best way to get a solid knowledge of web game development. After that, you can pick any framework you like and use it for your projects. Frameworks are just tools built...
...orking as expected, you can always try to debug that or just write your own solutions in pure JavaScript. Note: If you are interested in learning about 2D web game development using a game library, consult this series' counterpart, 2D breakout game using Phaser. Note: This series of articles can be used as material for hands-on game development workshops. You can also make use of the Gamedev Canvas Content Kit based on this tutorial if you want to give a talk about game development in general. Next steps Ok, let's get started! Head to the first chapter-- Create the Canvas and draw on it. Next >> ...
Initialize the framework - Game development
This is the first of 16 tutorials to learn how to use Gamedev Phaser. After completing this tutorial you can find the source code for this section at Gamedev-Phaser-Content-Kit/demos/lesson01.html. Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML -- the Phaser framework will generate the required <canvas> element. The game's HTML The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element generated by the framework. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Gamedev Phaser Worksho...
...This tutorial uses Phaser V2 -- it won't work with the current version on Phas...
...t <script> element as shown above. Walking through what we have so far At this point we have a charset defined, <title> and some basic CSS in the header to reset the default margin and padding. We also have a <script> element to apply the Phaser source code to the page. The body contains a second <script> element, where we will write the JavaScript code to render the game and control it. The <canvas> element is generated automatically by the framework. We are initializing it by creating a new Phaser.Game object and assigning it to the game variable. The parameters are: The width and height to set the <canvas> to. The rendering method. The three options are AUTO, CANVAS and WEBGL. We can set one of the latter two explicitly or use AUTO to let Phaser decide which one to use. It usually use...
.... We are initializing it by creating a new Phaser.Game object and assigning it to the game variable. The parameters are: The width and height to set the <canvas> to. The rendering method. The three options are AUTO, CANVAS and WEBGL. We can set one of the latter two explicitly or use AUTO to let Phaser decide which one to use. It usually uses WebGL if available in the browser, falling back to Canvas 2D if not. The id of the <canvas> to use for rendering if one already exists on the page (we've specified null because we want Phaser to create its own.) The names to use for Phaser's three key functions that load and start the game, and update the game loop on every frame; we will use the same names to keep it clean. preload takes care of preloading the assets create is executed once ...
General asynchronous programming concepts - Learn web development
is very unrealistic. You would never calculate 10 million dates on a real web app! It does, however, serve to give you the basic idea. In our second example, simple-sync-ui-blocking.html (see it live), we simulate something slightly more realistic that you might come across on a real page. We block user interactivity with the rendering of the UI. ...
...ion dates on a real web app! ...
... with the rendering of the UI. In this example, we have two buttons: A "Fill canvas" button that when clicked fills the available <canvas> with 1 million blue circles. A "Click me for alert" button that when clicked shows an alert message. function expensiveOperation() { for(let i = 0; i < 1000000; i++) { ctx.fillStyle = 'rgba(0,0,255, 0.2)'; ctx.beginPath(); ctx.arc(random(0, canvas.width), random(0, canvas.height), 10, degToRad(0), degToRad(360), false); ctx.fill() } } fillBtn.addEventListener('click', expensiveOperation); alertBtn.addEventListener('click', () => alert('You clicked me!') ); If you click the first button and then quickly click the second one, you'll see that the alert does not appear until the circles have finished being rendered. The first operat...
...port multiple threads can use multiple cores to complete multiple tasks simultaneously: Thread 1: Task A --> Task B Thread 2: Task C --> Task D JavaScript is single-threaded JavaScript is traditionally single-threaded. Even with multiple cores, you could only get it to run tasks on a single thread, called the main thread. Our example from above is run like this: Main thread: Render circles to canvas --> Display alert() After some time, JavaScript gained some tools to help with such problems. Web workers allow you to send some of the JavaScript processing off to a separate thread, called a worker so that you can run multiple JavaScript chunks simultaneously. You'd generally use a worker to run expensive processes off the main thread so that user interaction is not blocked. Main thread: Ta...
Looping code - Learn web development
each successive iteration of the loop, which means that you can complete a whole load of tasks that are similar but slightly different -- if you've got a lot of different calculations to do, you want to do each different one, not the same one over and over again! Let's look at an example to perfectly illustrate why loops are such a good thing. ...
... to do each different one, not the same one over and over again! Let's look at an example to perfectly illustrate why loops are such a good thing. ...
... good thing. ...
...set="utf-8"> <title>Random canvas circles</title> <style> html { width: 100%; height: inherit; background: #ddd; } canvas { display: block; } body { margin: 0; } button { position: absolute; top: 5px; left: 5px; } </style> </head> <body> <button>Update</button> <canvas></canvas> <script> const btn = document.querySelector('button'); const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); let WIDTH = document.documentElement.clientWidth; let HEIGHT = document.documentElement.clientHeight; canvas.width = WIDTH; canvas.height = HEIGHT; function random(number) { return Math.floor(Math.rand...
Introduction to web APIs - Learn web development
e from the server can make the site or app feel much more responsive and "snappy". APIs that make this possible include XMLHttpRequest and the Fetch API. You may also come across the term Ajax, which describes this technique. Find out more about such APIs in Fetching data from the server. APIs for drawing and manipulating graphics are now widely supported in browsers -- the most popular ones are Canvas and WebGL, which allow you to programmatically update the pixel data contained in an HTML <canvas> element to create 2D and 3D scenes. For example, you might draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to it such as sepia or grayscale using the Canvas API, or create a complex 3D scene with lighting and textures using WebGL. Such APIs are often co...
...others to make constantly updating scenes like cartoons and games. Audio and Video APIs like HTMLMediaElement, the Web Audio API, and WebRTC allow you to do really interesting things with multimedia such as creating custom UI controls for playing audio and video, displaying text tracks like captions and subtitles along with your videos, grabbing video from your web camera to be manipulated via a canvas (see above) or displayed on someone else's computer in a web conference, or adding effects to audio tracks (such as gain, distortion, panning, etc). Device APIs are basically APIs for manipulating and retrieving data from modern device hardware in a way that is useful for web apps. Examples include telling the user that a useful update is available on a web app via system notifications (see the ...
...atures tend to be found hanging off the Document object, or an instance of an HTML element that you want to affect in some way, for example: const em = document.createElement('em'); // create a new em element const para = document.querySelector('p'); // reference an existing p element em.textContent = 'Hello there!'; // give em some text content para.appendChild(em); // embed em inside para The Canvas API also relies on getting a context object to use to manipulate things, although in this case, it's a graphical context rather than an audio context. Its context object is created by getting a reference to the <canvas> element you want to draw on, and then calling its HTMLCanvasElement.getContext() method: const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); An...
...text object to use to manipulate things, although in this case, it's a graphical context rather than an audio context. Its context object is created by getting a reference to the <canvas> element you want to draw on, and then calling its HTMLCanvasElement.getContext() method: const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); Anything that we want to do to the canvas is then achieved by calling properties and methods of the context object (which is an instance of CanvasRenderingContext2D), for example: Ball.prototype.draw = function() { ctx.beginPath(); ctx.fillStyle = this.color; ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI); ctx.fill(); }; Note: You can see this code in action in our bouncing balls demo (see it running live also). They use...
Debugging Frame Reflow
> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> </head> <body> <table width="100"> <tbody> <tr> <td>foo</td> </tr> </tbody> </table> </body> </html> will create the following log: VP 00B97C30 r=0 a=9180,4470 c=9180,4470 cnt=856 scroll 00B97EE0 r=0 a=9180,4470 c=9180,4470 cnt=857 scroll 00B97EE0 r=0 a=9180,4470 c=9180,4470 cnt=858 canvas 00B97C6C r=0 a=9180,UC c=9180,4470 cnt=859 area 02D7AFE4 r=0 a=9180,UC c=9180,UC cnt=860 text 02D7B150 r=0 a=9180,UC c=UC,UC cnt=861 text 02D7B150 d=0,0 block 02D7B210 r=0 a=9180,UC c=8940,UC cnt=862 block 02D7B210 d=8940,0 area 02D7AFE4 d=9180,120 canvas 00B97C6C d=9180,4470 scroll 00B97EE0 d=9180,4470 scroll 00B97EE0 d=9180,4470 VP 00B97C30 d=9180,4470 VP 00B97C30 r=1 ...
... text 02D7B150 d=0,0 block 02D7B210 r=0 a=9180,UC c=8940,UC cnt=862 block 02D7B210 d=8940,0 area 02D7AFE4 d=9180,120 canvas 00B97C6C d=9180,4470 scroll 00B97EE0 d=9180,4470 scroll 00B97EE0 d=9180,4470 VP 00B97C30 d=9180,4470 VP 00B97C30 r=1 a=9180,4470 c=9180,4470 cnt=863 scroll 00B97EE0 r=1 a=9180,4470 c=9180,4470 cnt=864 scroll 00B97EE0 r=1 a=9180,4470 c=9180,4470 cnt=865 canvas 00B97C6C r=1 a=9180,UC c=9180,4470 cnt=866 area 02D7AFE4 r=1 a=9180,UC c=9180,UC cnt=867 block 02D7B210 r=1 a=9180,UC c=8940,UC cnt=868 text 02D7B3F8 r=0 a=8940,UC c=UC,UC cnt=869 text 02D7B3F8 d=0,0 tblO 02D7B5F0 r=0 a=8940,UC c=0,0 cnt=870 tbl 02D7B7EC r=0 a=8940,UC c=1500,UC cnt=871 rowG 00B984A4 r=0 a=UC,UC c=UC,UC cnt=872 row 02D7BAF8 r=0 a=UC,UC c=...
...This viewport has the address 00B97C30. It is the initial reflow: r=0. Other reflow reasons are: incremental reflow resize reflow style change reflow dirty reflow The available width is 9180 twips. The available height is 4470 twip...
...tmlFrameInner frameO htmlFrameOuter img image inline inline letter letter line line select select obj object page page place placeholder posInline positionedInline canvas canvas root root scroll scroll caption tableCaption cell tableCell bcCell bcTableCell col tableCol colG tableColGroup tbl table tblO tableOuter rowG tableRowGroup ...
Working with ArrayBuffers
bug 732936 includes a discussion of working with an ArrayBuffer. This feature is based on the following work: //github.com/RealityRipple/UXP/blob/master/js/src/ctypes/CTypes.cpp#3080 //github.com/RealityRipple/UXP/blob/master/js/src/vm/ArrayBufferObject.cpp#1301 Example 1 - Image Data The following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to ImageData of canvas. ...
...ure is based on the following work: //github.com/RealityRipple/UXP/blob/master/js/src/ctypes/CTypes.cpp#3080 //github.com/RealityRipple/UXP/blob/master/js/src/vm/ArrayBufferObject.cpp#1301 Example 1 - Image Data The following example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to ImageData of canvas. ...
...owing example illustrates how to transfer a byte array pointed by ctypes.uint8_t.ptr to ImageData of canvas. This example is based on the fact that the ImageData returned from CanvasRenderingContext2D.getImageData is a Uint8ClampedArray view for an ArrayBuffer. ...
...transfer a byte array pointed by ctypes.uint8_t.ptr to ImageData of canvas. This example is based on the fact that the ImageData returned from CanvasRenderingContext2D.getImageData is a Uint8ClampedArray view for an ArrayBuffer. The following codeblock provides a basic example of getting and setting Uint8ClampedArray and ArrayBuffer of ImageData: // context is a CanvasRenderingContext2D of some canvas var imageData = context.getImageData(x, y, w, h); var array = imageData.data; // array is a Uint8ClampedArray var buffer = imageData.data.buffer; // buffer is a ArrayBuffer // incomingBuffer is a TypedArray var imageData2 = context.createImageData(w, h); imageData2.data.set(incomingBuffer); Further, if you have a byte array pixelBuffer, and you need to create ImageData from it. The data proper...
ImageBitmapRenderingContext - Web APIs
This was previously named transferImageBitmap(), but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage. ...
... This interface is available in both the window and the worker context. Methods ImageBitmapRenderingContext.transferFromImageBitmap() Displays the given ImageBitmap in the canvas associated with this rendering context. Ownership of the ImageBitmap is transferred to the canvas. ...
...This was previously named transferImageBitmap(), but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage. ...
...Its context id (the first argument to HTMLCanvasElement.getContext() or OffscreenCanvas.getContext()) is "bitmaprenderer". This interface is available in both the window and the worker context. Methods ImageBitmapRenderingContext.transferFromImageBitmap() Displays the given ImageBitmap in the canvas associated with this rendering context. Ownership of the ImageBitmap is transferred to the canvas. This was previously named transferImageBitmap(), but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage. Specifications Specification Status Comment HTML Living StandardThe definition of 'ImageBitmapRenderingContext' in that specification. Living Standard ...
ImageCapture - Web APIs
e ImageCapture requires some place to capture an image from, the example below starts with a device's media device (in other words a camera). This example shows, roughly, a MediaStreamTrack extracted from a device's MediaStream. The track is then used to create an ImageCapture object so that takePhoto() and grabFrame() can be called. Finally, it shows how to apply the results of these calls to a canvas object. var imageCapture; function onGetUserMediaButtonClick() { navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); }) .catch(error => console.log(error)); } function onGrabFrameButtonClick() { imageCapture...
...ediaButtonClick() { navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); }) .catch(error => console.log(error)); } function onGrabFrameButtonClick() { imageCapture.grabFrame() .then(imageBitmap => { const canvas = document.querySelector('#grabFrameCanvas'); drawCanvas(canvas, imageBitmap); }) .catch(error => console.log(error)); } function onTakePhotoButtonClick() { imageCapture.takePhoto() .then(blob => createImageBitmap(blob)) .then(imageBitmap => { const canvas = document.querySelector('#takePhotoCanvas'); drawCanvas(canvas, imageBitmap); }) .catch(error => console.log(error...
...rameCanvas'); drawCanvas(canvas, imageBitmap); }) .catch(error => console.log(error)); } function onTakePhotoButtonClick() { imageCapture.takePhoto() .then(blob => createImageBitmap(blob)) .then(imageBitmap => { const canvas = document.querySelector('#takePhotoCanvas'); drawCanvas(canvas, imageBitmap); }) .catch(error => console.log(error)); } /* Utils */ function drawCanvas(canvas, img) { canvas.width = getComputedStyle(canvas).width.split('px')[0]; canvas.height = getComputedStyle(canvas).height.split('px')[0]; let ratio = Math.min(canvas.width / img.width, canvas.height / img.height); let x = (canvas.width - img.width * ratio) / 2; let y = (canvas.height - img.height * ratio) / 2; canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); ...
...canvas, img) { canvas.width = getComputedStyle(canvas).width.split('px')[0]; canvas.height = getComputedStyle(canvas).height.split('px')[0]; let ratio = Math.min(canvas.width / img.width, canvas.height / img.height); let x = (canvas.width - img.width * ratio) / 2; let y = (canvas.height - img.height * ratio) / 2; canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio); } document.querySelector('video').addEventListener('play', function() { document.querySelector('#grabFrameButton').disabled = false; document.querySelector('#takePhotoButton').disabled = false; }); Specifications Specification Status Comment MediaStream I...
Path2D.addPath() - Web APIs
Web › API › Path2D › addPath
Syntax void path.addPath(path [, transform]); Parameters path A Path2D path to add. transform Optional A DOMMatrix to be used as the transformation matrix for the path that is added. (Technically a DOMMatrixInit object). Examples Adding a path to an existing path This example adds one path to another. HTML <canvas id="canvas"></canvas> JavaScript First, we create two separate Path2D objects, each of which contains a rectangle made using the rect() method. We then create a matrix using document.createElementNS() and createSVGMatrix(). ...
...rst, we create two separate Path2D objects, each of which contains a rectangle made using the rect() method. We then create a matrix using document.createElementNS() and createSVGMatrix(). We then add the second path to the first using addPath(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill(). ...
... objects, each of which contains a rectangle made using the rect() method. We then create a matrix using document.createElementNS() and createSVGMatrix(). We then add the second path to the first using addPath(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill(). ...
...h contains a rectangle made using the rect() method. We then create a matrix using document.createElementNS() and createSVGMatrix(). We then add the second path to the first using addPath(), also applying the matrix to move the second path to the right. Finally, we draw the first path (which now contains both rectangles) using fill(). ...
WebGL2RenderingContext - Web APIs
The WebGL2RenderingContext interface implements all members of the WebGLRenderingContext interface. Some methods of the WebGL 1 context can accept additional values when used in a WebGL 2 context. You will find this info noted on the WebGL 1 reference pages. ...
...The WebGL2RenderingContext interface implements all members of the WebGLRenderingContext interface. Some methods of the WebGL 1 context can accept additional values when used in a WebGL 2 context. You will find this info noted on the WebGL 1 reference pages. ...
...The WebGL2RenderingContext interface implements all members of the WebGLRenderingContext interface. ...
...The WebGL2RenderingContext interface implements all members of the WebGLRenderingContext interface. Some methods of the WebGL 1 context can accept additional values when used in a WebGL 2 context. You will find this info noted on the WebGL 1 reference pages. ...
WebGLRenderingContext.texImage2D() - Web APIs
ensional texture image. ...
...ment? pixels); void gl.texImage2D(target, level, internalformat, format, type, HTMLVideoElement? pixels); void gl.texImage2D(target, level, internalformat, format, type, ImageBitmap? ...
... gl.RGB: Discards the alpha components and reads the red, green and blue components. gl.RGBA: Red, green, blue and alpha components are read from the color buffer. gl.LUMINANCE: Each color component is a luminance component, alpha is 1.0. gl.LUMINANC...
...must be used if type is gl.UNSIGNED_BYTE. A Uint16Array must be used if type is either gl.UNSIGNED_SHORT_5_6_5, gl.UNSIGNED_SHORT_4_4_4_4, gl.UNSIGNED_SHORT_5_5_5_1, gl.UNSIGNED_SHORT or ext.HALF_FLOAT_OES. A Uint32Array must be used if type is gl.UNSIGNED_INT or ext.UNSIGNED_INT_24_8_WEBGL. A Float32Array must be used if type is gl.FLOAT. ImageData, HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap. offset (WebGL 2 only) A GLintptr byte offset into the WebGLBuffer's data store. Used to upload data to the currently bound WebGLTexture from the WebGLBuffer bound to the PIXEL_UNPACK_BUFFER target. Return value None. Examples gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); Specifications Specific...
Window.devicePixelRatio - Web APIs
resolution in CSS pixels. A value of 1 indicates a classic 96 DPI (76 DPI on some platforms) display, while a value of 2 is expected for HiDPI/Retina displays. Other values may be returned as well in the case of unusually low resolution displays or, more often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 DPI. ...
...n CSS pixels. A value of 1 indicates a classic 96 DPI (76 DPI on some platforms) display, while a value of 2 is expected for HiDPI/Retina displays. Other values may be returned as well in the case of unusually low resolution displays or, more often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 DPI. ...
...ed as well in the case of unusually low resolution displays or, more often, when a screen has a higher pixel depth than simply double the standard resolution of 96 or 76 DPI. Examples Correcting resolution in a <canvas> A <canvas> can appear too blurry on retina screens. Use window.devicePixelRatio to determine how much extra pixel density should be added to allow for a sharper image. HTML <canvas id="canvas"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // Set display size (css pixels). var size = 200; canvas.style.width = size + "px"; canvas.style.height = size + "px"; // Set actual size in memory (scaled to account for extra pixel density). var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry c...
...nvas"></canvas> JavaScript var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); // Set display size (css pixels). var size = 200; canvas.style.width = size + "px"; canvas.style.height = size + "px"; // Set actual size in memory (scaled to account for extra pixel density). var scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas. canvas.width = Math.floor(size * scale); canvas.height = Math.floor(size * scale); // Normalize coordinate system to use css pixels. ctx.scale(scale, scale); ctx.fillStyle = "#bada55"; ctx.fillRect(10, 10, 300, 300); ctx.fillStyle = "#ffffff"; ctx.font = '18px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var x = size / 2; var y = size / 2; var textString = "I love MDN"; ctx.fillTex...
Web APIs
Web › API
d interfaces (object types) that you may be able to use while developing your Web app or site. Web APIs are typically used with JavaScript, although this doesn't always have to be the case. Specifications This is a list of all the APIs that are available. ...
...KeywordValue CSSMathProduct CSSMathSum CSSMathValue CSSMediaRule CSSNamespaceRule CSSNumericValue CSSOMString CSSPageRule CSSPositionValue CSSPrimitiveValue CSSPseudoElement CSSRule CSSRuleList CSSStyleDeclaration CSSStyleRule CSSStyleSheet CSSStyleValue CSSSupportsRule CSSUnitValue CSSUnparsedValue CSSValue CSSValueList CSSVariableReferenceValue Cache CacheStorage CanvasCaptureMediaStreamTrack CanvasGradient CanvasImageSource CanvasPattern CanvasRenderingContext2D CaretPosition ChannelMergerNode ChannelSplitterNode CharacterData ChildNode Client Clients Clipboard ClipboardEvent ClipboardItem CloseEvent Comment CompositionEvent ConstantSourceNode ConstrainBoolean ConstrainDOMString ConstrainDouble ConstrainULong ContentIndex ContentIndexEvent Convolver...
...ntryValue FormDataEvent FullscreenOptions G GainNode Gamepad GamepadButton GamepadEvent GamepadHapticActuator Geolocation GeolocationCoordinates GeolocationPosition GeolocationPositionError GeometryUtils GestureEvent GlobalEventHandlers Gyroscope H HTMLAnchorElement HTMLAreaElement HTMLAudioElement HTMLBRElement HTMLBaseElement HTMLBaseFontElement HTMLBodyElement HTMLButtonElement HTMLCanvasElement HTMLCollection HTMLContentElement HTMLDListElement HTMLDataElement HTMLDataListElement HTMLDetailsElement HTMLDialogElement HTMLDivElement HTMLDocument HTMLElement HTMLEmbedElement HTMLFieldSetElement HTMLFontElement HTMLFormControlsCollection HTMLFormElement HTMLFrameSetElement HTMLHRElement HTMLHeadElement HTMLHeadingElement HTMLHtmlElement HTMLHyperlinkElementUtils HTMLIFrameE...
...terator NodeList NonDocumentTypeChildNode Notation Notification NotificationAction NotificationEvent NotifyAudioAvailableEvent O OES_element_index_uint OES_fbo_render_mipmap OES_standard_derivatives OES_texture_float OES_texture_float_linear OES_texture_half_float OES_texture_half_float_linear OES_vertex_array_object OVR_multiview2 OfflineAudioCompletionEvent OfflineAudioContext OffscreenCanvas OrientationSensor OscillatorNode OverconstrainedError P PageTransitionEvent PaintWorklet PannerNode ParentNode PasswordCredential Path2D PayerErrors PaymentAddress PaymentCurrencyAmount PaymentDetailsBase PaymentDetailsUpdate PaymentItem PaymentMethodChangeEvent PaymentRequest PaymentRequestEvent PaymentRequestUpdateEvent PaymentResponse PaymentValidationErrors Pbkdf2Params Performance...
Linear-gradient Generator - CSS: Cascading Style Sheets
ic="axis-rotation" data-info="rotation" data-min="-180" data-value="0" data-max="180"></div> </div> </div> <div id="tool-section" class="section"> <div class="title"> Tool settings </div> <div class="property"> <div class="name"> alpha background </div> <div id="canvas-bg"></div> <div id="add-axis" class="button"> add line </div> </div> <div id="order"> <div id="gradient-axes"></div> <div id="gradient-order"></div> </div> </div> </div> <div id="output"> <div class="css-property"> <span class="proper...
...ze !important; } /** * Main Container */ #container { width: 1000px; height: 100%; display: table; margin: 0 auto; } #gradient-container { width: 450px; height: 250px; min-width: 8px; min-height: 8px; margin: 100px auto; border: 1px solid #DDD; position: relative; } #gradient-container[data-alpha="true"]:after { content: ""; width: 100%; height: 100%; background: url('images/canvas-pattern.png'); position: absolute; z-index: -1; } /** * Gradient Axis */ .gradient-axis { width: 125%; height: 4px; margin: -3px 0 0 0; border: 1px solid #CCC; position: absolute; top: 50%; left: 0; opacity: 0.5; } .gradient-axis[data-active='true'] { opacity: 1; z-index: 1; } .gradient-axis:after { content: ""; width: 25px; height: 100%; background-color: #CCC; position: ...
... #controls .ui-input-slider[data-topic="axis-rotation"] { } #controls .ui-dropdown { width: 130px; height: 24px; } #controls .ui-dropdown-select { line-height: 24px; } #controls .ui-dropdown-list { height: 66px; line-height: 2.5em; overflow: hidden; } #delete-axis { margin: 0 38px 0 0; float: right !important; } /* Tool controls */ #tool-section .property .name { width: 150px; } #canvas-bg { width: 16px; height: 16px; margin: 5px; background: url("images/toggle-background.png") center right no-repeat; } #canvas-bg:hover { cursor: pointer; } #canvas-bg[data-alpha='false'] { background-position: center left; } #canvas-bg[data-alpha='true'] { background-position: center right; } /* Order gradients */ #order { margin-left: 24px; } #gradient-axes { width: 100%; height...
...lete_point_btn)="" (lg_axes.length="" (this.getattribute('data-state')="==" (update_output)="" *="" **="" +="" ++i)="" 4)="" 500);="" :="" <="" activeaxis.deleteactivepoint();="" activeaxis.updatepointcolor(color);="" activeaxis.updatepointposition(color);="" add_axis_btn.removeattribute('data-state');="" axes_menu="getElemById('gradient-axes');" axesmanager.init();="" box="" button="getElemById('canvas-bg');" button.addeventlistener('click',="" code="prefix" container="" container.setattribute('data-alpha',="" container;="" createstartaxis(-18);="" createstartaxis(18);="" delete_point_btn="getElemById('delete-point');" delete_point_btn.addeventlistener('click',="" delete_point_btn.setattribute('data-state',="" dropdownmanager.init();="" dropdownmanager.subscribe('axis-unit',="" for(var="" funct...
Demos of open web technologies
Mozilla supports a wide variety of exciting open web technologies, and we encourage their use. This page offers links to interesting demonstrations of these technologies. If you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
... Mozilla supports a wide variety of exciting open web technologies, and we encourage their use. This page offers links to interesting demonstrations of these technologies. If you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...ng open web technologies, and we encourage their use. This page offers links to interesting demonstrations of these technologies. If you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
...onstrations of these technologies. If you know of a good demonstration or application of open web technology, please add a link to the appropriate section here. ...
enable-background - SVG: Scalable Vector Graphics
h>, and <symbol> Context notes Value accumulate | new [ <x> <y> <width> <height> ]? ...
... <height> ]? ...
...round image canvas and onto the target device. Otherwise, there is no current background image canvas, so graphics elements are only rendered onto the target device. new [ <x> <y> <width> <height> ]? This value enables the ability of children of the current container element to access the background image. It also indicates that a new (i.e., initially transparent black) background image canvas is established and that in effect all children of the current container element shall be rendered into the new background image canvas in addition to being rendered onto the target device. The optional <x>, <y>, <width>, and <height> parameters are <number> values that indicate the subregion of the container element's user space where access to the background image is allowed to happen. Those v...
... Negative values for <width> or <height> are forbidden. If one, two, or three values are specified or if neither <width> nor <height> are specified, the BackgroundImage and BackgroundAlpha of a filter primitive are processed as if background image processing were not enabled. ...
GLSL Shaders - Game development
ith good WebGL support, such as the latest Firefox or Chrome. Create a directory to store your experiments in. Save a copy of the latest minimized Three.js library inside your directory. HTML structure Here's the HTML structure we will use. ...
...The <script> element in the <head> includes the Three.js library in the page; we will write our code into three script tags in the <body> tag: The first one will contain the vertex shader. The second one will contain the fragment shader. The third one will contain the actual JavaScript code generating the sce...
...Our example doesn't do much but there are many more cool things you can do with shaders -- check out some really cool ones on ShaderToy for inspiration and to learn from their sources. ...
Desktop mouse and keyboard controls - Game development
pPressed = true; } } The keyUpHandler looks almost exactly the same as the keyDownHandler above, but instead of setting the pressed variables to true, we would set them to false. ...
...e; } } The keyUpHandler looks almost exactly the same as the keyDownHandler above, but instead of setting the pressed variables to true, we would set them to false. ...
...Then the pressed key variables are checked and the playerX and playerY variables (that we define earlier just after leftPressed and the others) holding the position of the ship are adjusted by a given amount, let's say 5 pixels. Then the player's ship is drawn on the screen and the next draw is called from within the requestAnimationFrame.
Square tilemaps implementation: Static maps - Game development
The tile atlas A tilemap might use one or several atlases -- or spritesheets -- that contain all of the tile images. This is the atlas we will be using as an example, which features five different tiles: To draw a tile from the atlas into the canvas we make use of the drawImage() method in a canvas 2D context. ...
... load images, etc., which is all explained in the Canvas API tutorial, as well as the basic information included in our Tilemaps introduction article. The tile atlas A tilemap might use one or several atlases -- or spritesheets -- that contain all of the tile images. This is the atlas we will be using as an example, which features five different tiles: To draw a tile from the atlas into the canvas we make use of the drawImage() method in a canvas 2D context. We need to supply the atlas image, the coordinates and dimensions of the tile inside the atlas, and the target coordinates and size (a different tile size in here would scale the tile.) So, for instance, to draw the tree tile, which is the third in the atlas, at the screen coordinates (128, 320), we would call drawImage() with these v...
... 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 ], getTile: function(col, row) { return this.tiles[row * map.cols + col] } }; Rendering the map We can render the map by iterating over its columns and rows. This snippets assumes the following definitions: context: A 2D canvas context. tileAtlas: An image object containing the tile atlas. map: The tilemap object discussed above. for (var c = 0; c < map.cols; c++) { for (var r = 0; r < map.rows; r++) { var tile = map.getTile(c, r); if (tile !== 0) { // 0 => empty tile context.drawImage( tileAtlas, // image (tile - 1) * map.tsize, // source x 0, // source y map.tsize, /...
Collision detection - Game development
For the sake of this tutorial we will do it the easiest way possible. ...
...For the sake of this tutorial we will do it the easiest way possible. ...
...We have the bricks appearing on the screen already, but the game still isn't that interesting as the ball goes through them. We need to think about adding collision detection so it can bounce off the bricks and break them. It's our decision how to implement this, of course, but it can be tough to calculate whether the ball is touching the rectangle or not because there are no helper functions in Canvas for this. For the sake of this tutorial we will do it the easiest way possible. We will check if the center of the ball is colliding with any of the given bricks. This won't give a perfect result every time, and there are much more sophisticated ways to do collision detection, but this will work fine for teaching you the basic concepts. A collision detection function To kick this all off we wan...
Track the score and win - Game development
Destroying the bricks is really cool, but to be even more awesome the game could award points for every brick a user hits, and keep count of the total score. Counting the score If you can see your score throughout the game, eventually you can impress your friends. You need a variable to record the score. Add the following into your JavaScript, after the rest of your variables: var score = 0; You also need a drawScore() function, to create and update the score display. ...
...ble to record the score. Add the following into your JavaScript, after the rest of your variables: var score = 0; You also need a drawScore() function, to create and update the score display. Add the following after the collisionDetection() function: function drawScore() { ctx.font = "16px Arial"; ctx.fillStyle = "#0095DD"; ctx.fillText("Score: "+score, 8, 20); } Drawing text on a canvas is similar to drawing a shape. The font definition looks exactly like the one in CSS -- you can set the size and font type in the font() method. Then use fillStyle() to set the color of the font and fillText() to set the actual text that will be placed on the canvas, and where it will be placed. The first parameter is the text itself -- the code above shows the current number of points -- and the...
... To award a score each time a brick is hit, add a line to the collisionDetection() function to increment the value of the score variable each time a collision is detected. ...
Load the assets and print them on screen - Game development
Add the following line between the game initialization code (our var game... block) and the preload() function: var ball; Note: For the sake of this tutorial, we will use global variables. The purpose of the tutorial is to teach Phaser-specific approaches to game development rather than dwelling on subjective best approaches. Loading the ball sprite Loading images and printing them on our canvas is a lot easier using Phaser than using pure JavaScript. To load the asset, we will use the game object created by Phaser, executing its load.image() method. Add the following new line just inside the preload() function, at the bottom: function preload() { // ... game.load.image('ball', 'img/ball.png'); } The first parameter we want to give the asset is the name that will be used acros...
...ctory in the same place as your index.html file. Now, to show it on the screen we will use another Phaser method called add.sprite(); add the following new code line inside the create() function as shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } This will add the ball to the game and render it on the screen. ...
... shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } This will add the ball to the game and render it on the screen. The first two parameters are the x and y coordinates of the canvas where you want it added, and the third one is the name of the asset we defined earlier. That's it -- if you load your index.html file you will see the image already loaded and rendered on the canvas! Compare your code You can check the finished code for this lesson for yourself in the live demo below, and play with it to better understand how it works: Next steps Printing out the ball was easy; next, we'll try moving the ball on screen. << PreviousNext >> ...
Visual JS GE - Game development
Installation and setup First of all download Visual-js from bitbucket. Extract the package into your root folder. ...
... Installation and setup First of all download Visual-js from bitbucket. Extract the package into your root folder. ...
... Installation and setup First of all download Visual-js from bitbucket. Extract the package into your root folder. ...
From object to iframe — other embedding technologies - Learn web development
like <object>, and the lesser-used <embed>, and they were very useful at the time. They have since fallen out of fashion due to many problems, including accessibility, security, file size, and more; these days most mobile devices don't support such plugins anymore, and desktop support is on the way out. Finally, the <iframe> element appeared (along with other ways of embedding content, such as <canvas>, <video>, etc.) This provides a way to embed an entire web document inside another one, as if it were an <img> or other such element, and is used regularly today. With the history lesson out of the way, let's move on and see how to use some of these. Active learning: classic embedding uses In this article we are going to jump straight into an active learning section, to immediately give you a...
...ave completly removed all Flash functionality. Any existing Flash content will be inaccessable after that date. So what should you do? If you need interactivity, HTML and JavaScript can readily get the job done for you with no need for Java applets or outdated ActiveX/BHO technology. Instead of relying on Adobe Flash, you should use HTML5 video for your media needs, SVG for vector graphics, and Canvas for complex images and animations. Peter Elst was already writing some years ago that Adobe Flash is rarely the right tool for the job. As for ActiveX, even Microsoft's Edge browser no longer supports it. Test your skills! You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information b...
... for much beyond including third-party content like maps and videos on your pages. As you become more experienced, however, you are likely to start finding more uses for them. There are many other technologies that involve embedding external content besides the ones we discussed here. We saw some in earlier articles, such as <video>, <audio>, and <img>, but there are others to discover, such as <canvas> for JavaScript-generated 2D and 3D graphics, and <svg> for embedding vector graphics. We'll look at SVG in the next article of the module. Previous Overview: Multimedia and embedding Next In this module Images in HTML Video and audio content From <object> to <iframe> -- other embedding technologies Adding vector graphics to the Web Responsive images Mozilla splash page ...
Test your skills: Functions - Learn web development
t prints a random name from the provided array (names) to the provided paragraph (para), and then run it once. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...the provided array (names) to the provided paragraph (para), and then run it once. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
... Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
Accessibility API cross-reference
d to the front, for temporary content. E.g., tooltips may be drawn on the glass pane layer. GLASS_PANE GLASS_PANE n/a Multiple adjacent panes that can be sized relative to each other by dragging a grippy on their border SPLIT_PANE SPLIT_PANE n/a An object that can be drawn into and is used to trap events. ...
...mporary content. E.g., tooltips may be drawn on the glass pane layer. GLASS_PANE GLASS_PANE n/a Multiple adjacent panes that can be sized relative to each other by dragging a grippy on their border SPLIT_PANE SPLIT_PANE n/a An object that can be drawn into and is used to trap events. ...
...ASS_PANE GLASS_PANE n/a Multiple adjacent panes that can be sized relative to each other by dragging a grippy on their border SPLIT_PANE SPLIT_PANE n/a An object that can be drawn into and is used to trap events. ...
Experimental features in Firefox
a preference for higher (or lower) contrast in the presentation of web content. Refer to bug 1506364 for more details. Release channel Version added Enabled by default? Nightly 80 No Developer Edition 80 No Beta 80 No Release 80 No Preference name layout.css.prefers-contrast.enabled APIs Graphics: Canvas, WebGL, and WebGPU Interface: OffscreenCanvas The OffscreenCanvas interface provides a canvas that can be rendered offscreen. It is available in both the window and worker contexts. See bug 1390089 for more details. Release channel Version added Enabled by default? Nightly 44 No Developer Edition 44 No Beta 44 No Release ...
...OffscreenCanvas interface provides a canvas that can be rendered offscreen. It is available in both the window and worker contexts. See bug 1390089 for more details. Release channel Version added Enabled by default? Nightly 44 No Developer Edition 44 No Beta 44 No Release 44 No Preference name gfx.offscreencanvas.enabled Hit regions Whether the mouse coordinates are within a particular area on the canvas is a common problem to solve. The hit region API allows you define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. Release channel Version added Enabled by default? Nightly 30 No D...
...Currently, there are no WebGL extensions being tested by Firefox. ...
nsITaskbarPreviewController
1.9.2 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Clients should provide their own implementation of this interface. Depending on whether the controller is connected to an nsITaskbarTabPreview or nsITaskbarWindowPreview, only certain methods and attributes need to be implemented. Method overview boolean drawPreview(in nsIDOMCanvasRenderingContext2D ctx); boolean drawThumbnail(in nsIDOMCanvasRenderingContext2D ctx, in unsigned long width, in unsigned long height); boolean onActivate(); void onClick(in nsITaskbarPreviewButton button); void onClose(); Attributes Attribute Type Description height unsigned long The height in pixels of the preview image. T...
...r cannot alter these values. The controller and its supporting code, however, may change this values at any time. Methods drawPreview() Invoked by nsITaskbarPreview when it needs to render the preview. The specified context is attached to a surface with the controller's width and height, the values of which are obtained immediately prior to calling this method. boolean drawPreview( in nsIDOMCanvasRenderingContext2D ctx ); Parameters ctx An nsIDOMCanvasRenderingContext2D object representing the drawing context into which the preview is to be rendered. Note that this context is not actually attached to a canvas element. Return value true if you want a frame drawn around the preview, otherwise false. drawThumbnail() Invoked by the taskbar preview when it needs to draw the thumbnail...
...object representing the drawing context into which the preview is to be rendered. Note that this context is not actually attached to a canvas element. Return value true if you want a frame drawn around the preview, otherwise false. drawThumbnail() Invoked by the taskbar preview when it needs to draw the thumbnail in the taskbar's application preview window. boolean drawThumbnail( in nsIDOMCanvasRenderingContext2D ctx, in unsigned long width, in unsigned long height ); Parameters ctx An nsIDOMCanvasRenderingContext2D object representing the drawing context into which the thumbnail is to be rendered. Note that this context is not actually attached to a canvas element. width The width of the surface backing the drawing context. height The height of the surface backing the draw...
AnalyserNode.getFloatFrequencyData() - Web APIs
// fill the Float32Array with data returned from getFloatFrequencyData() analyser.getFloatFrequencyData(myDataArray); Drawing a spectrum The following example shows basic usage of an AudioContext to connect a MediaElementAudioSourceNode to an AnalyserNode. While the audio is playing, we collect the frequency data repeatedly with requestAnimationFrame() and draw a "winamp bargraph style" to a <canvas> element. For more complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). <!doctype html> <body> <script> const audioCtx = new AudioContext(); //Create audio source //Here, we use an audio file, but this could also be e.g. microphone input const audioEle = new Audio(); audioEle.src = 'my-audio.mp3';//insert file name here audioEle.a...
...'; const audioSourceNode = audioCtx.createMediaElementSource(audioEle); //Create analyser node const analyserNode = audioCtx.createAnalyser(); analyserNode.fftSize = 256; const bufferLength = analyserNode.frequencyBinCount; const dataArray = new Float32Array(bufferLength); //Set up audio node network audioSourceNode.connect(analyserNode); analyserNode.connect(audioCtx.destination); //Create 2D canvas const canvas = document.createElement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const canvasCtx = canvas.getContext('2d'); canvasCtx.clearRect(0, 0, canvas.width, canvas.height); function draw() { //Schedule next redraw requestAnimationFr...
...as.style.left = 0; canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const canvasCtx = canvas.getContext('2d'); canvasCtx.clearRect(0, 0, canvas.width, canvas.height); function draw() { //Schedule next redraw requestAnimationFrame(draw); //Get spectrum data analyserNode.getFloatFrequencyData(dataArray); //Draw black background canvasCtx.fillStyle = 'rgb(0, 0, 0)'; canvasCtx.fillRect(0, 0, canvas.width, canvas.height); //Draw spectrum const barWidth = (canvas.width / bufferLength) * 2.5; let posX = 0; for (let i = 0; i < bufferLength; i++) { const barHeight = (dataArray[i] + 140) * 2; canvasCtx.fillStyle = 'rgb(' + Math.floor(barHeight + 100) + ', 50, 50)'; canvasCtx.fillRect(posX, canvas.height - barHei...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
Game development Gaming is one of the most popular computer activities. New technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. ...
... << Previous Congratulations! You finished the Canvas tutorial! This knowledge will help you to make great 2D graphics on the web. More examples and tutorials There are a variety of demos and further explanations about canvas on these sites: Codepen.io Front End Developer Playground & Code Editor in the Browser. HTML5 Canvas Tutorials Examples for most canvas APIs. Game development Gaming is one of the most popular computer activities. New technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. Other Web APIs These APIs might be useful when working further with canvas and graphics: WebGL Advanced API for rendering complex graphics, including 3D. SVG Scalable Vect...
... in order to allow them to scale smoothly regardless of the size at which they're drawn. Web Audio The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more. Questions Stack Overflow Questions tagged with "canvas". Comments about this tutorial - the MDN documentation community If you have any comments about this tutorial or want to thank us, feel free to reach out to us! << Previous ...
Element: mousedown event - Web APIs
n is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property onmousedown Examples The following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an HTML5 canvas. Its functionality is simple: the thickness of the line is set to 1, and the color is always black. When the page loads, constants myPics and context are created to store a reference to the canvas and the 2d context we will use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to t...
...isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. ...
... drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mo...
Element: mousemove event - Web APIs
The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property onmousemove Examples The following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an HTML5 canvas. Its functionality is simple: the thickness of the line is set to 1, and the color is always black. When the page loads, constants myPics and context are created to store a reference to the canvas and the 2d context we will use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. ...
...isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. ...
... drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mo...
Element: mouseup event - Web APIs
ice (such as a mouse or trackpad) is released while the pointer is located inside it. mouseup events are the counterpoint to mousedown events. Bubbles Yes Cancelable Yes Interface MouseEvent Event handler property onmouseup Examples The following example uses the mousedown, mousemove, and mouseup events to allow the user to draw on an HTML5 canvas. Its functionality is simple: the thickness of the line is set to 1, and the color is always black. When the page loads, constants myPics and context are created to store a reference to the canvas and the 2d context we will use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to t...
...isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. ...
... drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mo...
WEBGL_debug_renderer_info - Web APIs
e, this extensions is disabled. This extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. ...
...his extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. ...
...ailable to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. ...
WEBGL_debug_shaders.getTranslatedShaderSource() - Web APIs
.getExtension('WEBGL_debug_shaders').getTranslatedShaderSource(shader); Parameters shader A WebGLShader to get the translated source from. Return value A String containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader() has not yet been called or, the translation for the shader failed. ...
...').getTranslatedShaderSource(shader); Parameters shader A WebGLShader to get the translated source from. Return value A String containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader() has not yet been called or, the translation for the shader failed. ...
...derSource(shader); Parameters shader A WebGLShader to get the translated source from. Return value A String containing the translated shader source. An empty string is returned, if: no source has been defined or, WebGLRenderingContext.compileShader() has not yet been called or, the translation for the shader failed. ...
WebGLRenderingContext.getSupportedExtensions() - Web APIs
] See also the WebGLRenderingContext.getExtension() method to get a specific extension object. ...
...] See also the WebGLRenderingContext.getExtension() method to get a specific extension object. ...
...] See also the WebGLRenderingContext.getExtension() method to get a specific extension object. ...
WebGLRenderingContext.texSubImage2D() - Web APIs
t texture. ...
...LCanvasElement? pixels); void gl.texSubImage2D(target, level, xoffset, yoffset, format, type, HTMLVideoElement? pixels); void gl.texSubImage2D(target, level, xoffset, yoffset, format, type, ImageBitmap? ...
... following objects can be used as a pixel source for the texture: ArrayBufferView, A Uint8Array must be used if type is gl.UNSIGNED_BYTE. A Uint16Array must be used if type is either gl.UNSIGNED_SHORT_5_6_5, gl.UNSIGNED_SHORT_4_4_4_4, gl.UNSIGNED_SHORT_5_5_5_1, or ext.HALF_FLOAT_OES. A Float32Array must be used if type is gl.FLOAT. ImageData, HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap. offset (WebGL 2 only) A GLintptr byte offset into the WebGLBuffer's data store. Used to upload data to the currently bound WebGLTexture from the WebGLBuffer bound to the PIXEL_UNPACK_BUFFER target. Return value None. Examples gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, image); Specifications Specific...
WebGLRenderingContext.viewport() - Web APIs
inates. Syntax void gl.viewport(x, y, width, height); Parameters x A GLint specifying the horizontal coordinate for the lower left corner of the viewport origin. Default value: 0. y A GLint specifying the vertical coordinate for the lower left corner of the viewport origin. Default value: 0. width A non-negative Glsizei specifying the width of the viewport. Default value: width of the canvas. ...
... coordinate for the lower left corner of the viewport origin. Default value: 0. y A GLint specifying the vertical coordinate for the lower left corner of the viewport origin. Default value: 0. width A non-negative Glsizei specifying the width of the viewport. Default value: width of the canvas. height A non-negative Glsizei specifying the height of the viewport. Default value: height of the canvas. Return value None. Errors thrown If either width or height is a negative value, a gl.INVALID_VALUE error is thrown. Examples When you first create a WebGL context, the size of the viewport will match the size of the canvas. However, if you resize the canvas, you will need to tell the WebGL context a new viewport setting. In this situation, you can use gl.viewport. gl.viewport(0, 0, canva...
...n value None. Errors thrown If either width or height is a negative value, a gl.INVALID_VALUE error is thrown. Examples When you first create a WebGL context, the size of the viewport will match the size of the canvas. However, if you resize the canvas, you will need to tell the WebGL context a new viewport setting. In this situation, you can use gl.viewport. gl.viewport(0, 0, canvas.width, canvas.height); The viewport width and height are clamped to a range that is implementation dependent. To get this range, you can use the MAX_VIEWPORT_DIMS constant, which returns an Int32Array. gl.getParameter(gl.MAX_VIEWPORT_DIMS); // e.g. Int32Array[16384, 16384] To get the current viewport, query the VIEWPORT constant. gl.getParameter(gl.VIEWPORT); // e.g. Int32Array[0, 0, 640, 480] Specific...
WebGL constants - Web APIs
A list is provided below. ...
...A list is provided below. ...
...A list is provided below. ...
WebGL best practices - Web APIs
pdated as the browser window resizes, and older resources above the limit must be purged. Keeping the application's VRAM usage under this cap will help to avoid out-of-memory errors and associated instability. Consider rendering to a smaller backbuffer size A common (and easy) way to trade off quality for speed is rendering into a smaller backbuffer, and upscaling the result. Consider reducing canvas.width and height and keeping canvas.style.width and height at a constant size. Batch draw calls (prefer fewer-but-larger draw calls) Fewer, larger draw operations will generally improve performance. If you have 1000 sprites to paint, try to do it as a single drawArrays() or drawElements() call. It's common to use "degenerate triangles" if you need to draw discontinuous objects as a single draw...
... Use requestPostAnimationFrame not requestAnimationFrame While it's well-known that apps should use requestAnimationFrame ("RAF") instead of setTimeout (et al) to redraw on-demand, what's less well-known is that non-trivial WebGL apps should often not render within a RAF callback. RAF callbacks (and their microtasks/p...
...mationFrame ("RPAF") is the first JS run at the beginning of each Browser content frame. That is, it's the first JS run after RAF callbacks and the Browser content (transaction) presentation step. (RPAF explainer) This allows as much time as possible for rendering each frame. devicePixelRatio and high-dpi rendering Handling devicePixelRatio != 1.0 is tricky. While the common approach is to set canvas.width = width * devicePixelRatio, this will cause moire artifacts with non-integer values of devicePixelRatio, as is common with UI scaling on Windows, as well as zooming on all platforms. Instead, we can use non-integer values for CSS's top/bottom/left/right to fairly reliably 'pre-snap' our canvas to whole integer device coordinates. Demo: https://jdashg.github.io/misc/webgl/device-pixel-pres...
WebGL: 2D and 3D graphics for the web - Web APIs
Web › API › WebGL API
WebGL (Web Graphics Library) is a JavaScript API for rendering high-performance interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. WebGL does so by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements. This conformance makes it possible for the API to take advantage of hardware graphics acceleration provided by the user's device. ...
...rovided by the user's device. Support for WebGL is present in Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+, Internet Explorer 11+, and Microsoft Edge build 10240+; however, the user's device must also have hardware that supports these features. The WebGL 2 API introduces support for much of the OpenGL ES 3.0 feature set; it's provided through the WebGL2RenderingContext interface. The <canvas> element is also used by the Canvas API to do 2D graphics on web pages. Reference Standard interfaces WebGLRenderingContext WebGL2RenderingContext WebGLActiveInfo WebGLBuffer WebGLContextEvent WebGLFramebuffer WebGLProgram WebGLQuery WebGLRenderbuffer WebGLSampler WebGLShader WebGLShaderPrecisionFormat WebGLSync WebGLTexture WebGLTransformFeedback WebGLUniformLocation WebGLV...
...r with tutorials to learn basics of webgl programming. WebGL Stats A site with statistics about WebGL capabilities in browsers on different platforms. Libraries glMatrix is a JavaScript matrix and vector library for high-performance WebGL apps. PhiloGL is a WebGL framework for data visualization, creative coding, and game development. Pixi.js is a fast, open-source 2D WebGL renderer. PlayCanvas is an open-source game engine. Sylvester is an open-source library for manipulating vectors and matrices. Not optimized for WebGL but extremely robust. three.js is an open-source, fully featured 3D WebGL library. Phaser is a fast, free and fun open source framework for Canvas and WebGL powered browser games. RedGL is an open-source 3D WebGL library. vtk.js is a JavaScript library for scienti...
Media buffering, seeking, and time ranges - Developer guides
rties: myAudio.buffered.length; // returns 2 myAudio.buffered.start(0); // returns 0 myAudio.buffered.end(0); // returns 5 myAudio.buffered.start(1); // returns 15 myAudio.buffered.end(1); // returns 19 To try out and visualize buffered time ranges we can write a little bit of HTML: <p> <audio id="my-audio" controls> <source src="music.mp3" type="audio/mpeg"> </audio> </p> <p> <canvas id="my-canvas" width="300" height="20"> </canvas> </p> and a little bit of JavaScript: window.onload = function(){ var myAudio = document.getElementById('my-audio'); var myCanvas = document.getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle...
... a little bit of JavaScript: window.onload = function(){ var myAudio = document.getElementById('my-audio'); var myCanvas = document.getElementById('my-canvas'); var context = myCanvas.getContext('2d'); context.fillStyle = 'lightgray'; context.fillRect(0, 0, myCanvas.width, myCanvas.height); context.fillStyle = 'red'; context.strokeStyle = 'white'; var inc = myCanvas.width / myAudio.duration; // display TimeRanges myAudio.addEventListener('seeked', function() { for (i = 0; i < myAudio.buffered.length; i++) { var startX = myAudio.buffered.start(i) * inc; var endX = myAudio.buffered.end(i) * inc; var width = endX - startX; context.fillRect(startX, 0, width, myCanvas.height); context.rect(startX, 0, width...
...Each red filled white rectangle represents a time range. Note: You can see the timerange code running live on JS Bin. Seekable The seekable attribute returns a TimeRanges object and tel...
Content categories - Developer guides
to other documents, or convey other out of band information. Elements belonging to this category are <base>, <command>, <link>, <meta>, <noscript>, <script>, <style> and <title>. Flow content Elements belonging to the flow content category typically contain text or embedded content. ...
...element was removed from the W3C HTML specification prior to HTML 5 being finalized, but is still part of the WHATWG specification and is at least partially supported by most browsers. Phrasing content Phrasing content defines the text and the mark-up it contains. Runs of phrasing content make up paragraphs. ...
... phrasing content <ins>, if it contains only phrasing content <link>, if the itemprop attribute is present <map>, if it contains only phrasing content <meta>, if the itemprop attribute is present Embedded content Embedded content imports another resource or inserts content from another mark-up language or namespace into the document. Elements that belong to this category include: <audio>, <canvas>, <embed>, <iframe>, <img>, <math>, <object>, <picture>, <svg>, <video>. Interactive content Interactive content includes elements that are specifically designed for user interaction. Elements that belong to this category include: <a>, <button>, <details>, <embed>, <iframe>, <keygen>, <label>, <select>, and <textarea>. Some elements belong to this category only under specific conditions: <...
Animation performance and frame rate - Web Performance
Animation on the web can be done via SVG, JavaScript, including <canvas> and WebGL, CSS animation, <video>, animated gifs and even animated PNGs and other image types. The performance cost of animating a CSS property can vary from one property to another, and animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate. For animated media, such as video and animated gifs, the main performance concern is file size - downloading the file size fast enough to not negatively impact performance is the greatest issue. Code based animations, be it CSS, SVG, <canvas>, webGL or other JavaScript animations, can cause performance issues even if the bandwidth footprint is small. These animations can consume CPU and/or cause jank. While performance is sensitiv...
... geometry for the elements. This operation is labeled "layout" but is also sometimes called "reflow". Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition". ...
...ation is labeled "layout" but is also sometimes called "reflow". Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition". The process a browser uses to paint updated changes to a canvas element is different. In the <canvas> scenario, the page layout is not changing. Rather, the page is being repainted, repeatedly, based on JavaScript canvas API functions. When a canvas is animating a drawing, the canvas animation can be described as a waterfall consisting of the following steps: These sequenced need to fit into a single frame, since the screen isn't updated until it is complete. CSS property cost In the context...
Compiling an Existing C Module to WebAssembly - WebAssembly
.1 is encoded as 0x000601 = 1537. Get an image from JavaScript into Wasm Getting the encoder's version number is great, but encoding an actual image would be more impressive. How do we do that? The first question you need to answer is: how do I get the image into wasm? Looking at the encoding API of libwebp, you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. ...
...s 0x000601 = 1537. Get an image from JavaScript into Wasm Getting the encoder's version number is great, but encoding an actual image would be more impressive. How do we do that? The first question you need to answer is: how do I get the image into wasm? Looking at the encoding API of libwebp, you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. ...
... API of libwebp, you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. Luckily, the Canvas API has CanvasRenderingContext2D.getImageData -- that gives you an Uint8ClampedArray containing the image data in RGBA: async function loadImage(src) { // Load image const imgBlob = await fetch(src).then(resp => resp.blob()); const img = await createImageBitmap(imgBlob); // Make canvas same size as image const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; // Draw image onto canvas const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return ctx.getImageData(0, 0, img.width, img.height); } Now it's "only" a matter of copying the data from JavaScript into wasm. For that, you need to expose two additional f...
Code snippets - Archive of obsolete content
Miscellaneous Miscellaneous useful code fragments HTML to DOM Using a hidden browser element to parse HTML to a window's DOM JavaScript libraries Here are some JavaScript libraries that may come in handy. StringView A library that implements a StringVi...
... Miscellaneous Miscellaneous useful code fragments HTML to DOM Using a hidden browser element to parse HTML to a window's DOM JavaScript libraries Here are some JavaScript libraries that may come in handy. StringView A library that implements a StringView view for JavaScript ty...
Index of archived content - Archive of obsolete content
Web Page Troubleshooting Unit Testing Using XPCOM without chrome Using third-party modules (jpm) Bootstrapped extensions Code snippets Alerts and Notifications Autocomplete Bookmarks Boxes Canvas code snippets Cookies Customizing the download progress bar Delayed Execution Dialogs and Prompts Downloading Files Drag & Drop Embedding SVG Examples and demos from articles File I/O Finding window handles Forms related code snippets HTML in XUL for rich...
... WinRegValue XPJS Components Proposal XRE XTech 2005 Presentations Directions of the Mozilla RDF engine Extending Gecko with XBL and XTF Mozilla E4X Rich Web SVG And Canvas In Mozilla XUL - Mozilla's XML User Interface Language XTech 2006 Presentations XUL Explorer XULRunner Application Update Article Building XULRunner Building XULRunner with Python CommandLine Components ...
XTech 2005 Presentations - Archive of obsolete content
at updates to either the DOM or the E4X object hierarchy show up in the other. Directions of the Mozilla RDF engine: website scripting, standards conformance and perfomance - Axel Hecht This presentation showed new developments in the Mozilla RDF engine. These include plans to expose the RDF API to public web content, as well as performance and correctness improvements. Rich Web: SVG And Canvas In Mozilla - Robert O'Callahan Today's Web browsers offer somewhat limited graphics capabilities to Web developers. Advances in hardware, especially graphics processors, offer the potential for far richer graphics in interactive applications. To realize this potential in Web applications, browsers must expose rich new graphics APIs to Web content. The Mozilla project will meet this challenge wit...
...ics capabilities to Web developers. Advances in hardware, especially graphics processors, offer the potential for far richer graphics in interactive applications. To realize this potential in Web applications, browsers must expose rich new graphics APIs to Web content. The Mozilla project will meet this challenge with two major new features to be delivered in Firefox 1.1: integrated SVG and a new canvas HTML element. Work is also underway "under the hood" on a new unified graphics architecture that uses 3D graphics processors to accelerate all rendering. This work provides additional benefits to Web developers such as the ability to apply SVG effects to HTML content. Extending Gecko with XBL and XTF - Brian Ryner This session explored ways to extend Mozilla/Firefox to handle new XML tags an...
Theme changes in Firefox 2 - Archive of obsolete content
.button-box .plain:focus > .button-box .styleLessBorderLess The default theme also includes styles for a[href] img, body, h1, h2, and html. safebrowser/browser-protection.css This file, new to Firefox 2, skins browser protection features. ...
...> .button-box .styleLessBorderLess The default theme also includes styles for a[href] img, body, h1, h2, and html. safebrowser/browser-protection.css This file, new to Firefox 2, skins browser protection features. ...
Square tilemaps implementation: Scrolling maps - Game development
This article also builds upon implementing static square tilemaps -- you should read that too if you've not done so already. The camera The camera is an object that holds information about which section of the game world or level is currently being shown. ...
...This article also builds upon implementing static square tilemaps -- you should read that too if you've not done so already. The camera The camera is an object that holds information about which section of the game world or level is currently being shown. ...
Bounce off the walls - Game development
code as it should look after completing this lesson at Gamedev-Phaser-Content-Kit/demos/lesson06.html. Now that physics have been introduced, we can start implementing collision detection into the game -- first we'll look at the walls. Bouncing off the world boundaries The easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the <canvas> element as walls and not let the ball move past them. In Phaser this can be easily accomplished using the collideWorldsBound property. Add this line right after the existing game.physics.enable() method call: ball.body.collideWorldBounds = true; Now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. To make this occur we have to set its bounciness. Ad...
...sics.enable() method call: ball.body.collideWorldBounds = true; Now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. To make this occur we have to set its bounciness. Add the following line below the previous one: ball.body.bounce.set(1); Try reloading index.html again -- now you should see the ball bouncing off all the walls and moving inside the canvas area. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps This is starting to look more like a game now, but we can't control it in any way -- it's high time we introduced the player paddle and controls. << PreviousNext >> ...
Build the brick field - Game development
Now, let's start creating the bricks themselves -- add an empty group first to contain the bricks, by adding the following line at the bottom of the initBricks() function: bricks = game.add.group(); We can loop through the rows and columns to create new brick on each iteration -- add the following ...
...ition is worked out as brickInfo.width plus brickInfo.padding, multiplied by the column number, c, plus the brickInfo.offset.left; the logic for the brickY is identical except that it uses the values for row number, r, brickInfo.height, and brickInfo.offset.top. Now every single brick can be placed in its correct place, with padding between each brick, and drawn at an offset from the left and top Canvas edges. Checking the initBricks() code Here is the complete code for the initBricks() function: function initBricks() { brickInfo = { width: 50, height: 20, count: { row: 3, col: 7 }, offset: { top: 50, left: 60 }, padding: 10 } bricks = game.add.group(); for(c=0; c<brickInfo.
Touch Event Horizon - Game development
This is a multi-player game relying on the Tap and Drag gestures. ...
...This is a multi-player game relying on the Tap and Drag gestures. ...
Tutorials - Game development
This page contains multiple tutorial series that highlight different workflows for effectively creating different types of web games. 2D breakout game using pure JavaScript In this step-by-step tutorial you'll implement a simple breakout clone using pure JavaScript. Along the way you will learn the basics of using the <canvas> element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states. 2D breakout game using Phaser In this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using thePhaser HTML5 game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, alo...
...series, except that this time you'll do it using thePhaser HTML5 game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, along with fundamental game mechanics. 2D maze game with device orientation This tutorial shows how to create a 2D maze game using HTML5, incorporating fundamentals such as collision detection and sprite placement on a <canvas>. This is a mobile game that uses the Device Orientation and Vibration APIs to enhance the gameplay and is built using the Phaser framework. 2D platform game with Phaser This tutorial series shows how to create a simple platform game using Phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more. ...
Visual typescript game engine - Game development
Written in typescript current version 3.1.3. Text editor used and recommended: Visual Studio Code. Luanch debugger configuration comes with this project. Physics engine based on Matter.js. Multiplatform video chat (for all browsers) implemented. SocketIO used for session staff. MultiRTC2 used for data transfer also for video chat. MultiRTC3 alias 'broadcaster' used for video chat. Client part To make all dependency works in build process we need some plugins. ...
...ivate gameList: any[]; /** * Implement default gamePlay variable's */ private defaultGamePlayLevelName: string = "level1"; private autoStartGamePlay: boolean = true; Start the dependency system from app.ts The first game template is Platformer. This is high-level programming in this software. Class GamePlay extends Platformer, it good for start. Class Starter is base class for my canvas part and matter.ts (matter.js) implementation. It is injected to the Platformer to make full operated work. gamesList args for IOC constructor is for now just symbolic for now. (WIP) In ioc, you can make strong class dependency relations. Use it for your own structural changes. Main dependency file // Symbolic for now const plarformerGameInfo = { name: "Crypto-Runner", title: "PLAY PLATF...
Accessible multimedia - Learn web development
ontent and what needs to be done to ensure its accessibility, ranging from simple text content to data tables, images, native controls such as form elements and buttons, and even more complex markup structures (with WAI-ARIA attributes). This article on the other hand looks at another general class of content that arguably isn't as easy to ensure accessibility for -- multimedia. Images, videos, <canvas> elements, Flash movies, etc., aren't as easily understood by screenreaders or navigated by the keyboard, and we need to give them a helping hand. But don't despair -- here we will help you navigate through the techniques available for making multimedia more accessible. Simple images We already covered simple text alternatives for HTML images in our HTML: A good basis for accessibility article...
...ially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video. Other multimedia content The above sections don't cover all types of multimedia content that you might want to put on a web page. You might also need to deal with games, animations, slideshows, embedded video, and content created using other available technologies such as: HTML5 canvas Flash Silverlight For such content, you need to deal with accessibility concerns on a case by case basis. In some cases it is not so bad, for example: If you are embedding audio content using a plugin technology like Flash or Silverlight, you can probably just provide an audio transcript in the same manner as we already showed above in the Transcript examples section. If you are embedding...
Index - Learn web development
lore what APIs are, and how to use some of the most common APIs you'll come across often in your development work. 57 Client-side storage API, Article, Beginner, CodingScripting, Guide, IndexedDB, JavaScript, Learn, Storage That's it for now. We hope you've found our rundown of client-side storage technologies useful. 58 Drawing graphics API, Article, Beginner, Canvas, CodingScripting, Graphics, JavaScript, Learn, WebGL At this point, you should have a useful idea of the basics of graphics programming using Canvas and WebGL and what you can do with these APIs, as well as a good idea of where to go for further information. Have fun! 59 Fetching data from the server API, Article, Beginner, CodingScripting, Fetch, JSON, JavaScript, Learn, Pro...
...to keep track of all the properties and methods in our person object as separate variables and functions, it would be inefficient and frustrating, and we'd run the risk of clashing with other variables and functions that have the same names. Objects let us keep the information safely locked away in their own package, out of harm's way. 68 Object building practice Article, Beginner, Canvas, CodingScripting, Guide, JavaScript, Learn, Objects, Tutorial, l10n:priority We hope you had fun writing your own real world random bouncing balls example, using various object and object-oriented techniques from throughout the module! This should have given you some useful practice in using objects, and good real world context. 69 Object prototypes Article, Beginner, CodingS...
Functions — reusable blocks of code - Learn web development
n both forms: functions and methods. You can check the full list of the built-in functions, as well as the built-in objects and their corresponding methods here. You've also seen a lot of custom functions in the course so far -- functions defined in your code, not inside the browser. Anytime you saw a custom name with parentheses straight after it, you were using a custom function. ...
...Every time we want to do that, we can just invoke the function with this: draw(); rather than having to write all that code out again every time we want to repeat it. And functions can contain whatever code you like -- you can even call other functions from inside functions. The above function for example calls the random() function three times, which is defined by the following code:...
Function return values - Learn web development
involves some values that need to be calculated by a function. After the function calculates the value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation. Using return values in your own functions To return a value from a custom function, you need to use the return keyword. ...
...e value, it can return the result so it can be stored in a variable; and you can use this variable in the next stage of the calculation. Using return values in your own functions To return a value from a custom function, you need to use the return keyword. We saw this in action recently in our random-canvas-circles.html example. ...
Implementing feature detection - Learn web development
n object Check whether a certain method or property (typically an entry point into using the API or other feature you are detecting for) exists in its parent Object. if("geolocation" in navigator) { ... } Property on element Create an element in memory using Document.createElement() and then check if a property exists on it. The example shown is a way of detecting HTML5 Canvas support. function supports_canvas() { return !!document.createElement('canvas').getContext; } if(supports_canvas()) { ... } Method on element return value Create an element in memory using Document.createElement() and then check if a method exists on it. If it does, check what value it returns. See Dive Into HTML5 Video Formats detection test. Property ...
...If it is, we run some code that gets your device's current location, and plots it on a Google Map. Summar...
imgIEncoder
INPUT_FORMAT_RGBA 1 Input is RGB each pixel is represented by four bytes: R, G, and B (in that order, regardless of host endianness). POST-MULTIPLIED alpha us used (For example 50% transparent red is 0xff000080) INPUT_FORMAT_HOSTARGB 2 Input is host-endian ARGB: On big-endian machines each pixel is therefore ARGB, and for little-endian machiens (Intel) each pixel is BGRA (This is used by canvas to match it's internal representation) PRE-MULTIPLIED alpha is used (That is, 50% transparent red is 0x80800000, not 0x80ff0000) Possible values for outputOptions. Multiple values are semicolon-separated. PNG: ---- transparency=[yes|no|none] -- default: "yes" Overrides default from input format. "no" and "none" are equivalent. APNG: ----- The following options can be used with startIm...
...orever. The following options can be used for each frame, with addImageFrame(): transparency=[yes|no|none] -- default: "yes" Overrides default from input format. "no" and "none" are equivalent. delay=# -- default: "500" Number of milliseconds to display the frame, before moving to the next frame. dispose=[none|background|previous] -- default: "none" What to do with the image's canvas before rendering the next frame. See APNG spec. blend=[source|over] -- default: "source" How to render the new frame on the canvas. See APNG spec. xoffset=# -- default: "0" yoffset=# -- default: "0" Where to draw the frame, relative to the canvas. JPEG: ----- quality=# -- default: "92" Quality of compression, 0-100 (worst-best). Quality >= 90 prevents down-sampling of the c...
nsIDocShell
boolean Whether this docshell can execute scripts based on its hierarchy. The rule of thumb here is that we disable js if this docshell or any of its parents disallow scripting, unless the only reason for js being disabled in this docshell is a parent docshell having a document that is in design mode. In that case, we explicitly allow scripting on the current docshell. Read only. canvasHasFocus boolean Tells the docshell whether the canvas should have focus. Called by the focus manager when the user tabs to the frame rather than an element. Obsolete since Gecko 1.9.2 channelIsUnsafe boolean Find out if the currently loaded document came from a suspicious channel (such as a JAR channel where the server-returned content type is not a known JAR type). Read only...
... Read only. isInUnload boolean Find out whether the docshell is currently in the middle of a page transition (after the onunload event has fired, but before the new document has been set up) Read only. isOffScreenBrowser boolean If true, this docshell is not visible in the traditional sense, but is being actively rendered to the screen (such as by being painted to a canvas), and should be treated accordingly. layoutHistoryState nsILayoutHistoryState loadedTransIndex long Keeps track of the previous SHTransaction index and the current SHTransaction index at the time that the doc shell begins to load. Used for ContentViewer eviction. Read only. loadType unsigned long Load type for the document. Valid states are defined...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
The ImageBitmapRenderingContext.transferFromImageBitmap() method displays the given ImageBitmap in the canvas associated with this rendering context. The ownership of the ImageBitmap is transferred to the canvas as well. This method was previously named transferImageBitmap(), but was renamed in a spec change. The old name is being kept as an alias to avoid code breakage. Syntax void ImageBitmapRenderingContext.transferFromImageBitmap(bitmap) Parameters bitmap An ImageBitmap object to transfer. Examples HTML <canvas id="htmlCanvas"></canvas> JavaScript var htmlCanvas = document.getElementById("htmlCanvas").getContext("bitmaprenderer"); // Draw a WebGL scene offscreen var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawi...
...p An ImageBitmap object to transfer. Examples HTML <canvas id="htmlCanvas"></canvas> JavaScript var htmlCanvas = document.getElementById("htmlCanvas").getContext("bitmaprenderer"); // Draw a WebGL scene offscreen var offscreen = new OffscreenCanvas(256, 256); var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... // Transfer the current frame to the visible canvas var bitmap = offscreen.transferToImageBitmap(); htmlCanvas.transferFromImageBitmap(bitmap); Specifications Specification Status Comment HTML Living StandardThe definition of 'transferFromImageBitmap()' in that specification. Living Standard ...
ImageCapture.takePhoto() - Web APIs
d if it is available. Return value A Promise that resolves with a Blob. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by takePhoto() to copy the returned Blob to an <img> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
...n value A Promise that resolves with a Blob. Example This example is extracted from this Simple Image Capture demo. It shows how to use the Promise returned by takePhoto() to copy the returned Blob to an <img> element. For simplicy it does not show how to instantiate the ImageCapture object. ...
Path2D() - Web APIs
Web › API › Path2D › Path2D
isting of SVG path data. Syntax new Path2D(); new Path2D(path); new Path2D(d); Parameters path Optional When invoked with another Path2D object, a copy of the path argument is created. d Optional When invoked with a string consisting of SVG path data, a new path is created from that description. Examples Creating and copying paths This example creates and copies a Path2D path. <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let path1 = new Path2D(); path1.rect(10, 10, 100,100); let path2 = new Path2D(path1); path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and...
...10, 100,100); let path2 = new Path2D(path1); path2.moveTo(220, 60); path2.arc(170, 60, 50, 0, 2 * Math.PI); ctx.stroke(path2); Using SVG paths This example creates a Path2D path using SVG path data. The path will move to point (M10 10) and then move horizontally 80 points to the right (h 80), then 80 points down (v 80), then 80 points to the left (h -80), and then back to the start (Z). <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let p = new Path2D('M10 10 h 80 v 80 h -80 Z'); ctx.fill(p); Specification Specification Status Comment HTML Living StandardThe definition of 'Path2D()' in that specification. Living Standard Initial definition. ...
RenderingContext - Web APIs
RenderingContext is a WebIDL typedef which can refer to any one of the interfaces that represent a graphics rendering context within a <canvas> element: CanvasRenderingContext2D, WebGLRenderingContext, or WebGL2RenderingContext. By using the shorthand RenderingContext, methods and properties which can make use of any of these interfaces can be specified and written more easily; since <canvas> supports several rendering systems, it's helpful from a specification and browser implementation perspective to have a shorthand that means "one of these interfaces." As such, RenderingContext is an implementation detail, and isn't something web developers directly use. There is no RenderingContext interface, and there are no objects which implement type RenderingContext. The primary use of this type is...
...ms, it's helpful from a specification and browser implementation perspective to have a shorthand that means "one of these interfaces." As such, RenderingContext is an implementation detail, and isn't something web developers directly use. There is no RenderingContext interface, and there are no objects which implement type RenderingContext. The primary use of this type is the definition of the <canvas> element's HTMLCanvasElement.getContext() method, which returns a RenderingContext (meaning it returns any one of the rendering context types). Specifications Specification Status Comment HTML Living StandardThe definition of 'RenderingContext' in that specification. Living Standard Initial definition. ...
WebGL2RenderingContext.texImage3D() - Web APIs
The WebGLRenderingContext.texImage3D() method of the WebGL API specifies a three-dimensional texture image. ...
... offset A GLintptr byte offset into the WebGLBuffer's data store. Used to upload data to the currently bound WebGLTexture from the WebGLBuffer bound to the PIXEL_UNPACK_BUFFER target. Return value None. Examples gl.texImage3D(gl.TEXTURE_3D, 0, // level gl.RGBA, ...
WebGL2RenderingContext.texSubImage3D() - Web APIs
Possible values: gl.TEXTURE_3D: A thr...
...cts can be used as a pixel source for the texture: ArrayBufferView, A Uint8Array must be used if type is gl.UNSIGNED_BYTE. A Uint16Array must be used if type is either gl.UNSIGNED_SHORT_5_6_5, gl.UNSIGNED_SHORT_4_4_4_4, gl.UNSIGNED_SHORT_5_5_5_1, or ext.HALF_FLOAT_OES. A Float32Array must be used if type is gl.FLOAT. ImageBitmap, ImageData, HTMLImageElement, HTMLCanvasElement, HTMLVideoElement. offset A GLintptr byte offset into the WebGLBuffer's data store. Used to upload data to the currently bound WebGLTexture from the WebGLBuffer bound to the PIXEL_UNPACK_BUFFER target. Return value None. Examples gl.texSubImage3D(gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, 1, gl.RGBA, gl.UNSIGNED_BYTE, image); Specifications Speci...
WebGLRenderingContext.readPixels() - Web APIs
at or type is not an accepted value. A gl.INVALID_OPERATION error is thrown if type is gl.UNSIGNED_SHORT_5_6_5 and format is not gl.RGB. type is gl.UNSIGNED_SHORT_4_4_4_4 and format is not gl.RGBA. type does not match the typed array type of pixels. A gl.INVALID_FRAMEBUFFER_OPERATION error is thrown if the currently bound framebuffer is not framebuffer complete. ...
...e. A gl.INVALID_OPERATION error is thrown if type is gl.UNSIGNED_SHORT_5_6_5 and format is not gl.RGB. type is gl.UNSIGNED_SHORT_4_4_4_4 and format is not gl.RGBA. type does not match the typed array type of pixels. A gl.INVALID_FRAMEBUFFER_OPERATION error is thrown if the currently bound framebuffer is not framebuffer complete. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels); console.log(pixels); // Uint8Array Specifications Specification Status Comment WebGL 1.0The definition of 'readPixels' in that specification. Rec...
Detect WebGL - Web APIs
<< PreviousNext >> This example demonstrates how to detect a WebGL rendering context and reports the result to the user. Feature-detecting WebGL In this first example we are going to check whether the browser supports WebGL. To that end we will try to obtain the WebGL rendering context from a canvas element. The WebGL rendering context is an interface, through which you can set and query the state of the graphics machine, send data to the WebGL, and execute draw commands. Saving the state of the graphics machine within a single context interface is not unique to WebGL. This is also done in other graphics {{Glossary("API")}}, such as the canvas 2D rendering context. However, the properties and variables you can tweak are different for each API. <p>[ Here would go the result o...
...window load event handler, to make sure // DOM is fully loaded and styled before trying to manipulate it. window.addEventListener("load", function() { var paragraph = document.querySelector("p"), button = document.querySelector("button"); // Adding click event handler to button. button.addEventListener("click", detectWebGLContext, false); function detectWebGLContext () { // Create canvas element. The canvas is not added to the // document itself, so it is never displayed in the // browser window. var canvas = document.createElement("canvas"); // Get WebGLRenderingContext from canvas element. var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); // Report the result. if (gl && gl instanceof WebGLRenderingContext) { ...
WebGL tutorial - Web APIs
WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML <canvas> in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code (shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background. This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. ...
...ixed with other HTML elements and composited with other parts of the page or page background. This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with WebGL and will provide code snippets that may get you started in building your own content. Before you start Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly. In this tutorial Getting started with WebGL How to set u...
Functions and classes available to Web Workers - Web APIs
that works only in workers. 8 (8) No support No support No support FormData FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method. ? (should be in 39 (39)) ? (Yes) ? ImageData The underlying pixel data of an area of a canvas element. Manipulating such data can be a complex task better suited to be delegated to a Web Worker. 25 (25) No support No support No support IndexedDB Database to store records holding simple values and hierarchical objects. 37 (37), 42 (42) for IDBCursorWithValue. 10.0 (Yes) 10.1 Network Information API provides information about the system's con...
... No support No support URL Workers can use the static methods URL.createObjectURL and URL.revokeObjectURL with Blob objects accesible to the worker. Workers can also create a new URL using the URL() constructor and call any normal method on the returned object. 21 (21) and 26 (26) for URL() constructor No support No support No support WebGL with OffscreenCanvas WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true. No support No support No support WebSocket Creates and returns a new WebSocket object; this mimics the behavior...
XRSession.updateRenderState() - Web APIs
o be the near clip plane. No part of the scene on the viewer's side of this plane will be rendered. This is 0.1 meters (10 centimeters) by default. inlineVerticalFieldOfView Optional A floating-point value indicating the default field of view, in radians, to be used when computing the projection matrix for an inline XRSession. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property must not be specified for immersive sessions, so the value is null by default for immersive sessions. The default value is otherwise ? * 0.5 (half of the value of pi). Return value None. Exceptions This method may throw any of the following exceptions. These are true exceptions, since this method does not return a promise. InvalidStateError This may occur ...
.... The inlineVerticalFieldOfView property was set, but the session is immersive and therefore does not allow this property to be used. Examples This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an XRWebGLLayer. updateRenderState() is then called to associate the new XRWebGLLayer. function onXRSessionStarted(xrSession) { let glCanvas = document.createElement("canvas"); let gl = glCanvas.getContext("webgl", { xrCompatible: true }); loadWebGLResources(); xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl) }); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.updateRenderState()' in that specification. Working Draft Initial...
Web accessibility for seizures and physical reactions - Accessibility
ing web content accessibile for those with vestibular disorders, and how to measure and prevent content leading to seizures and / or other physical reactions. Overview Seizures Seizures caused by light are known as photosensitive epilepsy. Content that flickers, flashes, or blinks can trigger photosensitive epilepsy. Web technologies that use video, animated gifs, animated pngs, animated SVGs, Canvas, and CSS or JavaScript animations are all capable of content that can induce seizures or other incapacitating physical reactions. Certain visual patterns, especially stripes, can also cause physical reactions even though they are not animated. Photosensitive epilepsy is actually a kind of "reflex epilepsy"--seizures occurring in response to a trigger. In the case of photosensitive epilepsy, seizu...
...m the Web Animations model CSSWG.org drafts The Web Animations model is intended to provide the features necessary for expressing CSS Transitions [CSS-TRANSITIONS-1], CSS Animations [CSS-ANIMATIONS-1], and SVG [SVG11]. See Also MDN Accessibility: What users can to to browse more safely Accessibility: Understanding color and luminance Applying SVG effects to HTML Content Basic Animations (Canvas Tutorial) Canvas API CanvasRenderingContext2D.drawImage() <color> Document Object Model MediaQueryList Using dynamic styling information WebGL: 2D and 3D graphics for the web Color Color Tutorial: describing color Tom Jewett. Formula to Determine Brightness of RGB color Stack Exchange Discussion Thread How the Color Red Influences Our Behavior Scientific American By Susana Martinez-...
Mozilla CSS extensions - CSS: Cascading Style Sheets
ecoration -moz-anchor-decoration -moz-user-select -moz-all -moz-none width, min-width, and max-width -moz-min-content -moz-fit-content -moz-max-content -moz-available Pseudo-elements and pseudo-classes A - D ::-moz-anonymous-block eg@:- bug 331432 ::-moz-anonymous-positioned-block :-moz-any :-moz-any-link [Matches :link and :visited] :-moz-broken ::-moz-canvas ::-moz-color-swatch ::-moz-cell-content :-moz-drag-over F - I :-moz-first-node ::-moz-focus-inner ::-moz-focus-outer :-moz-focusring :-moz-full-screen :-moz-full-screen-ancestor :-moz-handler-blocked :-moz-handler-crashed :-moz-handler-disabled ::-moz-inline-table L :-moz-last-node :-moz-list-bullet :-moz-list-number :-moz-loading :-moz-locale-dir(ltr) :-moz-locale-...
...e-brighttext :-moz-lwtheme-darktext N - R :-moz-native-anonymous :-moz-only-whitespace ::-moz-page ::-moz-page-sequence ::-moz-pagebreak ::-moz-pagecontent :-moz-placeholderObsolete since Gecko 51 ::-moz-placeholderDeprecated since Gecko 51 ::-moz-progress-bar ::-moz-range-progress ::-moz-range-thumb ::-moz-range-track :-moz-read-only :-moz-read-write S ::-moz-scrolled-canvas ::-moz-scrolled-content ::-moz-scrolled-page-sequence ::-moz-selectionDeprecated since Gecko 62 :-moz-submit-invalid :-moz-suppressed ::-moz-svg-foreign-content T ::-moz-table ::-moz-table-cell ::-moz-table-column ::-moz-table-column-group ::-moz-table-outer ::-moz-table-row ::-moz-table-row-group :-moz-tree-cell :-moz-tree-cell-text :-moz-tree-cell-text(hover) :-moz-tree-c...
<color> - CSS: Cascading Style Sheets
may also be used in other contexts, but are not widely supported by browsers. The keywords in the following list are defined by the CSS Color Module Level 4 specification. Note that these keywords are case insensitive, but are listed here with mixed case for readability. ...
...rted by browsers. The keywords in the following list are defined by the CSS Color Module Level 4 specification. Note that these keywords are case insensitive, but are listed here with mixed case for readability. ...
Index - Developer guides
Web › Guide › Index
of web audio or video is playing 15 Writing Web Audio API code that works in every browser API You probably have already read the announcement on the Web Audio API coming to Firefox, and are totally excited and ready to make your until-now-WebKit-only sites work with Firefox, which uses the unprefixed version of the spec. 16 Audio and video manipulation Audio, Canvas, Examples, Guide, HTML5, Media, Video, Web Audio API, WebGL, developer recommendation The ability to read the pixel values from each frame of a video can be very useful. 17 Event developer guide DOM, Event, Guide, NeedsUpdate, events Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page a...
...ead use the standard touch events API, supported since Gecko/Firefox 6 with multi-touch support added in Gecko/Firefox 12. 26 Using device orientation with 3D transforms Advanced, CSS, DOM, NeedsUpdate, Orientation, Transforms This article provides tips on how to use device orientation information in tandem with CSS 3D transforms. 27 Graphics on the Web 2D, 3D, Canvas, Graphics, HTML5, SVG, Web, WebGL, WebRTC Websites and applications often need to present graphics, such as images.These articles provide insight into how you can accomplish this. 28 Guide to Web APIs API, Guide, Landing, Web The web includes a wide array of APIs that can be used from JavaScript to build increasingly more powerful and capable applications, running eithe...
User input and controls - Developer guides
ment can be made directly editable using the contenteditable attribute. <div contenteditable="true">? This text can be edited by the user. </div> Note: Compatibility information, examples and other resources can be found in the Content Editable guide. ...
...ultiple touch points at a time This example tracks multiple touch points at a time, allowing the user to draw in a <canvas> with more than one finger at a time. It will only work on a browser that supports touch events. Simple pointer lock demo We've written a simple pointer lock demo to show you how to use it to set up a simple control system. The demo uses JavaScript to draw a ball inside a <canvas> element. When you click the canvas, pointer lock is then used to remove the mouse pointer and allow you to move the ball directly using the mouse. contentEditable demo This is a working example showing how contenteditable can be used to create an editable document section, the state of which is then saved using LocalStorage. Tutorials Touch events Guide Managing screen orientation Using...
HTML attribute reference - HTML: Hypertext Markup Language
bmit button (type="submit"), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form. If this attribute is specified, it overrides the target attribute of the button's form owner. headers <td>, <th> IDs of the <th> elements which applies to this element. height <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video> Specifies the height of elements listed here. For all other elements, use the CSS height property. Note: In some instances, such as <div>, this is a legacy attribute, in which case the CSS height property should be used instead. hidden Global attribute Prevents rendering of given element, while keepin...
...to leave them unchanged. type <button>, <input>, <command>, <embed>, <object>, <script>, <source>, <style>, <menu> Defines the type of the element. usemap <img>, <input>, <object> value <button>, <data>, <input>, <li>, <meter>, <option>, <progress>, <param> Defines a default value which will be displayed in the element on page load. width <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video> For the elements listed here, this establishes the element's width. Note: For all other instances, such as <div>, this is a legacy attribute, in which case the CSS width property should be used instead. wrap <textarea> Indicates whether the text should be wrapped. Content versus IDL attributes ...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
autoplay guide for additional information about how to properly use autoplay. controls If this attribute is present, the browser will offer controls to allow the user to control audio playback, including volume, seeking, and pause/resume playback. crossorigin This enumerated attribute indicates whether to use CORS to fetch the related audio file. CORS-enabled resources can be reused in the <canvas> element without being tainted. The allowed values are: anonymous Sends a cross-origin request without a credential. In other words, it sends the Origin: HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin: HTTP header), the image will be tainted, ...
...P header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through Access-Control-Allow-Credentials: HTTP header), the image will be tainted and its usage restricted. When not present, the resource is fetched without a CORS request (i.e. without sending the Origin: HTTP header), preventing its non-tainted used in <canvas> elements. If invalid, it is handled as if the enumerated keyword anonymous was used. See CORS settings attributes for additional information. currentTime Reading currentTime returns a double-precision floating-point value indicating the current playback position, in seconds, of the audio. If the audio's metadata isn't available yet--thereby preventing you from knowing the media's start time ...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
Visual browsers will also hide the broken image icon if the alt is empty and the image failed to display. This attribute is also used when copying and pasting the image to text, or saving a linked image to a bookmark. crossorigin Indicates if the fetching of the image must be done using a CORS request. Image data from a CORS-enabled image returned from a CORS request can be reused in the <canvas> element without being marked "tainted". If the crossorigin attribute is not specified, then a non-CORS request is sent (without the Origin request header), and the browser marks the image as tainted and restricts access to its image data, preventing its usage in <canvas> elements. If the crossorigin attribute is specified, then a CORS request is sent (with the Origin request header); but if ...
... Allowed values: anonymous A CORS request is sent with credentials omitted (that is, no cookies, X.509 certificates, or Authorization request header). use-credentials The CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and the Authorization request header). If the server does not opt into sharing credentials with the origin sit...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
wn set of controls (e.g. when the controls attribute is specified). The allowed values are nodownload, nofullscreen and noremoteplayback. Use the disablePictureInPicture attribute if you want to disable the Picture-In-Picture mode (and the control). crossorigin This enumerated attribute indicates whether to use CORS to fetch the related image. CORS-enabled resources can be reused in the <canvas> element without being tainted. The allowed values are: anonymous Sends a cross-origin request without a credential. In other words, it sends the Origin: HTTP header without a cookie, X.509 certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin: HTTP header), the image will be tainted, ...
...P header with a cookie, a certificate, or performing HTTP Basic authentication. If the server does not give credentials to the origin site (through Access-Control-Allow-Credentials: HTTP header), the image will be tainted and its usage restricted. When not present, the resource is fetched without a CORS request (i.e. without sending the Origin: HTTP header), preventing its non-tainted used in <canvas> elements. If invalid, it is handled as if the enumerated keyword anonymous was used. See CORS settings attributes for additional information. currentTime Reading currentTime returns a double-precision floating-point value indicating the current playback position of the media specified in seconds. If the media has not started playing yet, the time offset at which it will begin is returned. Se...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
xt Markup Language HTML, HTML5, Landing, Web, l10n:priority HTML (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation (CSS) or functionality/behavior (JavaScript). 2 Allowing cross-origin use of images and canvas Advanced, CORS, Canvas, HTML, Image, Reference, Security, Storage, data HTML provides a crossorigin attribute for images that, in combination with an appropriate CORS header, allows images defined by the <img> element that are loaded from foreign origins to be used in a <canvas> as if they had been loaded from the current origin. 3 Applying color to HTML elements using CSS ...
... a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant. 75 <button>: The Button element Element, Forms, HTML, HTML forms, Reference, Web The HTML <button> element represents a clickable button, used to submit forms or anywhere in a document for accessible, standard button functionality. 76 <canvas>: The Graphics Canvas element Canvas, Element, HTML, HTML scripting, HTML5, Reference, Web Use the HTML <canvas> element with either the canvas scripting API or the WebGL API to draw graphics and animations. 77 <caption>: The Table Caption element Element, HTML, HTML Tables, HTML tabular data, Reference, Table Captions, Table Titles, Tables, Web, caption The HTML <c...
HTML: Hypertext Markup Language
Web › HTML
b. By uploading content to the Internet and linking it to pages created by other people, you become an active participant in the World Wide Web. HTML uses "markup" to annotate text, images, and other content for display in a Web browser. HTML markup includes special "elements" such as <head>, <title>, <body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datalist>, <details>, <embed>, <nav>, <output>, <progress>, <video>, <ul>, <ol>, <li> and many others. An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "<" and ">". The name of an element inside a tag is case insensitive. That is, it can be written in uppercase, lowercase, or a mixture. For example, the <title> tag can be wri...
...ns of content explaining how to use HTML to solve very common problems when creating a web page: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc. Advanced topics CORS enabled image The crossorigin attribute, in combination with an appropriate CORS header, allows images defined by the <img> element to be loaded from foreign origins and used in a <canvas> element as if they were being loaded from the current origin. CORS settings attributes Some HTML elements that provide support for CORS, such as <img> or <video>, have a crossorigin attribute (crossOrigin property), which lets you configure the CORS requests for the element's fetched data. Preloading content with rel="preload" The preload value of the <link> element's rel attribute allows yo...
Graphic design for responsive sites - Progressive web apps (PWAs)
any other type of interactivity you want. It is very powerful when combined with other technologies, although its complexity is a barrier for non-developers. SVG SVG, just like HTML/CSS, can be manipulated via JavaScript. So adding interactivity is not difficult. You can also add links direcly into SVG and can create animations using SMIL (Synchronized Multimedia Intergration Language). WebGL/Canvas You can create a canvas to draw interactive graphics on using the HTML <canvas> element, then use the Canvas API to create shapes, lines, import image files, create text, do compositing operations, and much more. Standard JavaScript can then be used to animate the image output, etc. You can create 2D imagery using the regular 2D canvas context, or 3D imagery using the more nascent WebGL API. Ca...
... more. Standard JavaScript can then be used to animate the image output, etc. You can create 2D imagery using the regular 2D canvas context, or 3D imagery using the more nascent WebGL API. Canvas is very powerful, but it needs to be used with caution. It is good for the visuals of games and complex data visualisions, but for standard user interface elements it is not very efficient. In addition, Canvases are just raster images, so the text created inside them is not accessible, plus they don't scale well. ...
Positions - SVG: Scalable Vector Graphics
<< PreviousNext >> In this article, we examine how Scalable Vector Graphics (SVG) represents the positions and sizes of objects within a drawing context, including coordinate system and what a "pixel" measurement means in a scalable context. The grid For all elements, SVG uses a coordinate system or grid system similar to the one used by canvas (and by a whole lot of other computer drawing routines). That is, the top left corner of the document is considered to be the point (0,0), or point of origin. Positions are then measured in pixels from the top left corner, with the positive x direction being to the right, and the positive y direction being to the bottom. Note that this is slightly different than the way you're taught to graph as a kid (y axis is flipped). However, this i...
...bsolute units (ones with a dimensional identifier like "pt" or "cm") and so-called user units, that lack that identifier and are plain numbers. Without further specification, one user unit equals one screen unit. To explicitly change this behaviour, there are several possibilities in SVG. We start with the svg root element: <svg width="100" height="100"> The above element defines a simple SVG canvas with 100x100px. One user unit equals one screen unit. <svg width="200" height="200" viewBox="0 0 100 100"> The whole SVG canvas here is 200px by 200px in size. However, the viewBox attribute defines the portion of that canvas to display. These 200x200 pixels display an area that starts at user unit (0,0) and spans 100x100 user units to the right and to the bottom. This effectively zooms in on ...
JavaScript timers - Archive of obsolete content
be useful, for example, if you want to have your worker thread run code periodically instead of nonstop. Functions available to workers In addition to the standard JavaScript set of functions (such as String, Array, Object, JSON etc), there are a variety of functions available from the DOM to workers. This article provides a list of those. Basic animations Since we're using script to control canvas elements it's also very easy to make (interactive) animations. Unfortunately the canvas element was never designed to be used in this way (unlike Flash) so there are limitations. Timer.jsm The Timer.jsm JavaScript code module contains pure-JavaScript implementations of setTimeout and clearTimeout that are compatible with the DOM window functions, but that can be used by code that does not have ...
FAQ - Archive of obsolete content
Archive › Mozilla › Prism › FAQ
integrated into other products (like Firefox), then it won't necessarily continue to be called by this codename. Is Prism a platform? No, Prism is not a platform. Prism is built on top of the Mozilla platform and its Gecko rendering engine, just like Mozilla Firefox, so it provides the same capabilities to web applications that Firefox provides, including support for HTML, JavaScript, CSS, and <canvas>. At the same time, we're also working to increase the capabilities of those apps by adding features to the Web itself, like support for offline data storage and access to 3D graphics hardware, that will be available to web applications in both Prism and Firefox. How is Prism different from XULRunner? Prism is built on top of XULRUnner. Prism is a simple XULRunner application with the main porti...
Space Manager Detailed Design - Archive of obsolete content
Gecko Layout system, specifically Block Layout. See the High Level Design document for an overview of the Space Manager, and as an introduction to the classes, structures and algorithms container in this, the Detailed Design Document. nsSpaceManager The Space Manager is the central class is a group of classes that manage the occupied and available space that exists in horizontal bands across a canvas. The primary goal of the Space Manager is to provide information about those bands of space to support the CSS notion of floated elements. There are three important parts to the Space Manager API: the parts that deal with the coordinate space of the Space Manager, the parts that deal with the regions managed by the Space Manager, and the parts that manage float impact intervals. The class nsSpace...
XTech 2006 Presentations - Archive of obsolete content
cuments) and mechanisms for reordering content to allow the author to use good markup and appropriate layout. Microsummaries in Firefox and on the Web - Myk Melez Microsummaries are regularly-updated compilations of the most important and timely information on web pages. This talk demonstrates how Firefox will incorporate microsummaries into its UI, starting with bookmark labels. SVG and Canvas: Graphics for Web Apps - Vladimir Vukicevic This presentation examines some of the strengths and weaknesses of the HTML 'canvas' and SVG for adding rich graphical capabilities to web applications. Future browser graphics capabilities, both 2D and 3D, are also discussed. Converging Rich-Client and Web Application Development with Mozilla XULRunner (Open Office format) - Benjamin Smedberg Thi...
Table Reflow Internals - Archive of obsolete content
The initial chunk of an xml doc is loaded. The initial chunk of an html doc (or a subsequent chunk of an xml doc) is loaded. The container posts a dirty reflow command with itself as the target. Content is inserted, appended, or deleted through the DOM. ...
Anatomy of a video game - Game development
ur main loop contents // tFrame, from "function main ( tFrame )", is now a DOMHighResTimeStamp provided by rAF. } main(); // Start the cycle })(); Several other optimizations are possible and it really depends on what your game attempts to accomplish. Your game genre will obviously make a difference but it could even be more subtle than that. You could draw every pixel individually on a canvas or you could layer DOM elements (including multiple WebGL canvases with transparent backgrounds if you want) into a complex hierarchy. Each of these paths will lead to different opportunities and constraints. It is decision... time You will need to make hard decisions about your main loop: how to simulate the accurate progress of time. If you demand per-frame control then you will need to deter...
Introduction to game development for the Web - Game development
can do for you: Full Screen API This simple API lets your game take over the entire screen, thereby immersing the player in action. Gamepad API If you want your users to be able to use gamepads or other game controllers to work your game, you'll need this API. HTML and CSS Together, these two technologies let you build, style, and lay out your game's user interface. Part of HTML is the <canvas> element, which provides one way to do 2D graphics. HTML audio The <audio> element lets you easily play simple sound effects and music. If your needs are more involved, check out the Web Audio API for real audio processing power! IndexedDB A powerful data storage API for maintaining user data on their own computer or device. A great way to save game state and other information locally so it d...
Game distribution - Game development
ills, preferred frameworks or target platforms. It's all about picking the best tool for your particular task. Phonegap -- based on Cordova, this is the most popular tool for building/packaging JavaScript apps for native platforms. CocoonIO -- the most popular tool specifically for building HTML5 games for multiple native stores. It has it's own performance optimizations for games rendered on Canvas and supports many game frameworks. Ejecta -- a tool specifically for packaging games created with the ImpactJS framework for iOS, built by the ImpactJS author. It provides seamless integration with ImpactJS, but it only supports only one framework and app store. NW.js -- formerly known as Node-Webkit, this is the first choice when it comes to building a desktop game that works on Windows, Mac a...
Explaining basic 3D theory - Game development
of objects that are outside of the screen or behind other objects, and thus not visible, are not calculated. ...
Desktop gamepad controls - Game development
then the function returns true; false otherwise. Next, in the draw() function we do two things -- execute the gamepadUpdateHandler() function to get the current state of pressed buttons on every frame, and use the gamepadButtonPressedHandler() function to check the buttons we are interested to see whether they are pressed, and do something if they are: function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // ... gamepadUpdateHandler(); if(gamepadButtonPressedHandler(0)) { playerY -= 5; } else if(gamepadButtonPressedHandler(1)) { playerY += 5; } if(gamepadButtonPressedHandler(2)) { playerX -= 5; } else if(gamepadButtonPressedHandler(3)) { playerX += 5; } if(gamepadButtonPressedHandler(11)) { ...
Unconventional controls - Game development
'? <br />' + ' strength: ' + grabStrength + ''; } }); The code above is calculating and assigning the horizontalDegree, verticalDegree and grabStrength values that we will use later on, and outputting it in HTML so we can see the actual values. When those variables are up-to-date, we can use them in the draw() function to move the ship: function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // ... if(horizontalDegree > degreeThreshold) { playerX -= 5; } else if(horizontalDegree < -degreeThreshold) { playerX += 5; } if(verticalDegree > degreeThreshold) { playerY += 5; } else if(verticalDegree < -degreeThreshold) { playerY -= 5; } if(grabStrength == 1) { alert('BOOM!'); } ...
Efficient animation for web games - Game development
h the only ones semi-guaranteed to be fast across all browsers. Something to be careful of is that overflow may end up causing re-layout, or other expensive calculations. If you are setting a transform on something that would overlap its container's bounds, you may want to set overflow: hidden on that container for the duration of the animation. Use requestAnimationFrame When you are animating <canvas> content, or when your DOM animations absolutely must synchronise with canvas content animations, do make sure to use window.requestAnimationFrame, and not older methods such as window.setTimeout. Assuming you are running in an arbitrary browsing session, you can never really know how long the browser will take to draw a particular frame. requestAnimationFrame causes the browser to redraw and cal...
Techniques for game development - Game development
...
Extra lives - Game development
ing the alert right away : ball.events.onOutOfBounds.add(function(){ alert('Game over!'); location.reload(); }, this); We will assign a new function called ballLeaveScreen; delete the previous event handler (shown above) and replace it with the following line: ball.events.onOutOfBounds.add(ballLeaveScreen, this); We want to decrease the number of lives every time the ball leaves the canvas. Add the ballLeaveScreen() function definition at the end of our code: function ballLeaveScreen() { lives--; if(lives) { livesText.setText('Lives: '+lives); lifeLostText.visible = true; ball.reset(game.world.width*0.5, game.world.height-25); paddle.reset(game.world.width*0.5, game.world.height-5); game.input.onDown.addOnce(function(){ l...
Game over - Game development
ourth (bottom) will disappear, letting the ball fall off the screen if the paddle misses it. We need a way to detect this and act accordingly. Add the following lines just below the previous new one: ball.checkWorldBounds = true; ball.events.onOutOfBounds.add(function(){ alert('Game over!'); location.reload(); }, this); Adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onOutOfBounds event. When you click on the resulting alert, the page will be reloaded so you can play again. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Now the basic gameplay is in place let's make it more interesting by introducing bric...
Move the ball - Game development
ber the update() function and its definition? The code inside it is executed on every frame, so it's a perfect place to put the code that will update the ball's position on screen. Add the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } The code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame. Reload index.html and you should see the ball rolling across the screen. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps The next step is to add some basic collision detection, so our ball can bounce off the walls. This would take several lines of code -- a significantly ...
Player paddle and controls - Game development
our paddle by adding the following add.sprite() call inside the create() function -- add it right at the bottom: paddle = game.add.sprite(game.world.width*0.5, game.world.height-5, 'paddle'); We can use the world.width and world.height values to position the paddle exactly where we want it: game.world.width*0.5 will be right in the middle of the screen. In our case the world is the same as the Canvas, but for other types of games, like side-scrollers for example, the world will be bigger, and you can tinker with it to create interesting effects. As you'll notice if you reload your index.html at this point, the paddle is currently not exactly in the middle. Why? Because the anchor from which the position is calculated always starts from the top left edge of the object. We can change that to h...
Visual-js game engine - Game development
1) Click CREATE APPLICATION 2) Enter new application name in input prompt 3) Select folder for server part of application (important : www is not secure place) 4) Select folder for client part of application ( any ...
First contentful paint - MDN Web Docs Glossary: Definitions of Web-related terms
This excludes any content of iframes, but includes text with pending webfonts. This is the first time users could start consuming page content. ...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
Canonical order, CodingScripting, Glossary In CSS, canonical order is used to refer to the order in which separate values need to be specified (or parsed) or are to be serialized as part of a CSS property value. It is defined by the formal syntax of the property and normally refers to the order in which longhand values should be specified as part of a single shorthand value. 65 Canvas CodingScripting, Glossary, Graphics, HTML, JavaScript The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D and 3D shapes and bitmap images. 66 Card sorting Card sorting, Design, Glossary Card sorting is a simple technique used in Information architecture whereby people involved in the design of a website (or other type of product) a...
JavaScript - MDN Web Docs Glossary: Definitions of Web-related terms
nguage. Although "Java" and "JavaScript" are trademarks (or registered trademarks) of Oracle in the U.S. and other countries, the two programming languages are significantly different in their syntax, semantics, and use cases. JavaScript is primarily used in the browser, enabling developers to manipulate webpage content through the DOM, manipulate data with AJAX and IndexedDB, draw graphics with canvas, interact with the device running the browser through various APIs, and more. JavaScript is one of the world's most commonly-used languages, owing to the recent growth and performance improvement of APIs available in browsers. Origins and History Conceived as a server-side language by Brendan Eich (then employed by the Netscape Corporation), JavaScript soon came to Netscape Navigator 2.0 in Sep...
Polyfill - MDN Web Docs Glossary: Definitions of Web-related terms
The reason why polyfills are not used exclusively is for better functionality and better performance. Native implementations of APIs can do more and are faster than polyfills. ...
WebGL - MDN Web Docs Glossary: Definitions of Web-related terms
WebGL (Web Graphics Library) is a JavaScript API that draws interactive 2D and 3D graphics. The Khronos Group maintains WebGL, which is based on OpenGL ES 2.0. You can invoke WebGL within the HTML <canvas> element, which provides a rendering surface. All major browsers now support WebGL, but its availability depends also on external factors (e.g. GPU support). Learn more General knowledge WebGL on Wikipedia Check for WebGL support Technical Article WebGL on MDN Support table for WebGL ...
MDN Web Docs Glossary: Definitions of Web-related terms
lock (CSS) Block (scripting) Block cipher mode of operation Boolean Boot2Gecko Bootstrap Bounding Box Breadcrumb Brotli Browser Browsing context buffer C Cache Cacheable CalDAV Call stack Callback function Canonical order Canvas Card sorting CardDAV caret CDN Certificate authority Certified Challenge-response authentication Character Character encoding Character set Chrome CIA Cipher Cipher suite Ciphertext Class Client hints Closure CMS Code s...
CSS and JavaScript accessibility best practices - Learn web development
ere for some reason you can't control the markup that is used. Another way to improve accessibility for non-semantic JavaScript-powered widgets is to use WAI-ARIA to provide extra semantics for screen reader users. The next article will also cover this in detail. Complex functionality like 3D games are not so easy to make accessible -- a complex 3D game created using WebGL will be rendered on a <canvas> element, which has no facility at this time to provide text alternatives or other information for severely visually impaired users to make use of. It is arguable that such a game doesn't really have this group of people as a part of its main target audience, and it would be unreasonable to expect you to make it 100% accessible to blind people, however you could implement keyboard controls so it ...
create fancy boxes - Learn web development
t's not a square, we'll get an ellipsis rather than a circle ;) */ width : 4em; height : 4em; /* and let's turn the square into a circle */ border-radius: 100%; } Yes, we get a circle: Backgrounds When we talk about a fancy box, the core properties to handle that are background-* properties. When you start fiddling with backgrounds it's like your CSS box is turned into a blank canvas you'll fill. Before we jump to some practical examples, let's step back a bit as there are two things you should know about backgrounds. It's possible to set several backgrounds on a single box. They are stacked on top of each other like layers. Backgrounds can be either solid colors or images: solid color always fills the whole surface but images can be scaled and positioned. <div class=...
Sending forms through JavaScript - Learn web development
e at a time. To learn more about that, see the example in Accessing the element list's contents in HTMLFormElement.elements. Dealing with binary data If you use a FormData object with a form that includes <input type="file"> widgets, the data will be processed automatically. But to send binary data by hand, there's extra work to do. There are many sources for binary data, including FileReader, Canvas, and WebRTC. Unfortunately, some legacy browsers can't access binary data or require complicated workarounds. To learn more about the FileReader API, see Using files from web applications. The least complicated way of sending binary data is by using FormData's append() method, demonstrated above. If you have to do it by hand, it's trickier. In the following example, we use the FileReader API to...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
tinuously, as the code is calling requestAnimationFrame() recursively. Note: If you want to perform some kind of simple constant DOM animation, CSS Animations are probably faster. They are calculated directly by the browser's internal code, rather than JavaScript. If, however, you are doing something more complex and involving objects that are not directly accessible inside the DOM (such as 2D Canvas API or WebGL objects), requestAnimationFrame() is the better option in most cases. How fast does your animation run? The smoothness of your animation is directly dependent on your animation's frame rate and it is measured in frames per second (fps). The higher this number is, the smoother your animation will look, to a point. Since most screens have a refresh rate of 60Hz, the fastest frame r...
Test your skills: Events - Learn web development
e back when it is clicked again. The HTML should not be changed; just the JavaScript. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Events 2 Now we'll look at keyboard events. To pass this assessment you need to build an event handler that moves the circle around the provided canvas when the WASD keys are pressed on the keyboard. The circle is drawn with the function drawCircle(), which takes the folllowing parameters as inputs: x -- the x coordinate of the circle. y -- the y coordinate of the circle. size -- the radius of the circle. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own ed...
Client-side web APIs - Learn web development
log) or services (e.g. displaying custom Google Maps on your site, or using Facebook login to log in your users). This article looks at the difference between browser APIs and 3rd party APIs and shows some typical uses of the latter. Drawing graphics The browser contains some very powerful graphics programming tools, from the Scalable Vector Graphics (SVG) language, to APIs for drawing on HTML <canvas> elements, (see The Canvas API and WebGL). This article provides an introduction to the Canvas API, and further resources to allow you to learn more. Video and audio APIs HTML5 comes with elements for embedding rich media in documents -- <video> and <audio> -- which in turn come with their own APIs for controlling playback, seeking, etc. This article shows you how to do common tasks such as cre...
Basic math in JavaScript — numbers and operators - Learn web development
fore you type in the second line. Note that you can quite happily use other variables on the right hand side of each expression, for example: let x = 3; // x contains the value 3 let y = 4; // y contains the value 4 x *= y; // x now contains the value 12 Note: There are lots of other assignment operators available, but these are the basic ones you should learn now. Active learning: sizing a canvas box In this exercise, you will manipulate some numbers and operators to change the size of a box. The box is drawn using a browser API called the Canvas API. There is no need to worry about how this works -- just concentrate on the math for now. The width and height of the box (in pixels) are defined by the variables x and y, which are initially both given a value of 50. Open in new window I...
What is JavaScript? - Learn web development
HTML and CSS, creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every time you see a popup window appear on a page, or some new content displayed (as we saw above in our simple demo) for example, that's the DOM in action. The Geolocation API retrieves geographical information. This is how Google Maps is able to find your location and plot it on a map. The Canvas and WebGL APIs allow you to create animated 2D and 3D graphics. People are doing some amazing things using these web technologies --see Chrome Experiments and webglsamples. Audio and Video APIs like HTMLMediaElement and WebRTC allow you to do really interesting things with multimedia, such as play audio and video right in a web page, or grab video from your web camera and display it on someone e...
Adding features to our bouncing balls demo - Learn web development
operties, as follows: color -- 'white' size -- 10 Again, remember to define your inherited properties as parameters in the constructor, and set the prototype and constructor properties correctly. Defining EvilCircle()'s methods EvilCircle() should have four methods, as described below. draw() This method has the same purpose as Ball()'s draw() method: It draws the object instance on the canvas. It will work in a very similar way, so you can start by copying the Ball.prototype.draw definition. You should then make the following changes: We want the evil circle to not be filled in, but rather just have an outer line (stroke). You can achieve this by updating fillStyle and fill() to strokeStyle and stroke(). We also want to make the stroke a bit thicker, so you can see the evil circle...
CSS performance optimization - Learn web development
properties that do not trigger a reflow (and therefore also a repaint) very well. To improve performance, the node being animated can be moved off the main thread and onto the GPU. Properties that will lead to compositing include 3D transforms (transform: translateZ(), rotate3d(), etc.), animating transform and opacity, position: fixed, will-change, and filter. Some elements, including <video>, <canvas> and <iframe>, are also on their own layer. When an element is promoted as a layer, also known as composited, animating transform properties is done in the GPU, resulting in improved performance, especially on mobile. will-change property The CSS will-change property tells browsers which properties of an element are expected to change enabling browsers to set up optimizations before the element...
Perceived performance - Learn web development
er and provides the time, in ms, of when the page starts changing; but this change can be a simple background color update or something even less noticable. It doesn't indicate completeness and may report a time when nothing visible is painted. First Contentful Paint (FCP) reports the time when the browser first rendered anything of signifigance, be that text, foreground or background image, or a canvas or SVG; capturing the very beginning of the loading experience. But, just because there's content, doesn't mean it's useful content or that the user has content to consume. The First Meaningful Paint, or FMP, is the when content appears on the screen that is actually meaningful; which is a better metric for user-perceived loading experience, but still not ideal. Largest contentful paint (LCP) met...
Handling common HTML and CSS problems - Learn web development
block; on all of the new semantic elements (such as <article>, <aside>, etc.), but only in old versions of IE that don't recognise them (so, IE 8 and lower). This way new browsers can just use the code as normal, but older IE versions will be able to style these elements too. Note: See IE conditional comments for the best way to do this. More complex elements like HTML <video>, <audio>, and <canvas> (and other features besides) have natural mechanisms for fallbacks to be added, which work on the same principle as described above. You can add fallback content in between the opening and closing tags, and non-supporting browsers will effectively ignore the outer element and run the nested content. For example: <video id="video" controls preload="metadata" poster="img/poster.jpg"> <source s...
Handling common JavaScript problems - Learn web development
ations sometimes use prefixes too, although JavaScript uses camel case rather than hyphenation like CSS. For example, if a prefix was being used on a new shint API object called Object: Mozilla would use mozObject Chrome/Opera/Safari would use webkitObject Microsoft would use msObject Here's an example, taken from our violent-theremin demo (see source code), which uses a combination of the Canvas API and the Web Audio API to create a fun (and noisy) drawing tool: const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext(); In the case of the Web Audio API, the key entry points to using the API were supported in Chrome/Opera via webkit prefixed versions (they now support the unprefixed versions). The easy way to get around this situation is ...
Debugging Chrome
Unfortunately, it requires using --single-process which crashes on startup for me. To work around this I was able to record the GPU commands using apitrace. I copied the d3d9.dll into both C:\Users\jrmuizel\AppData\Local\Google\Chrome SxS\Application\22.0.1186.0 and C:\Users\jrmuizel\AppData\Local\Google\Chrome SxS\Application\. I'm not sure which is needed. I did TRACE_FILE=foo.txt and it created the trace file in "C:\Users\jrmuizel\AppData\Local\Google\Chrome SxS\Application\22.0.1183.0\foo.txt". I needed to run Chrome using --no-sandbox. I was then able to run PIX on d3dretrace. ...
Interface Compatibility
urity vulnerabilities or incompatibility with other browsers make it the only option. Any changes, including new features, must have super-review. One exception to this rule is APIs which are explicitly shipped with Mozilla prefixes as a technology preview. This includes CSS properties that begin with the -moz- prefix (e.g. -moz-box-shadow), or JavaScript APIs that begin with the moz prefix (e.g. canvasrenderingcontext.mozDrawText). These APIs may be removed or replaced with standard interfaces in future releases of Mozilla. Jetpack The Jetpack SDK and APIs are not yet complete. The stable version 1.0 of the Jetpack SDK is planned for later in 2010. Documented APIs which are shipped as part of the Jetpack SDK are designed to work in future versions of Firefox. Achieving this compatibility may ...
about:memory
-nodes | +--0.54 MB (02.03%) -- other | +--0.10 MB (00.36%) ++ (4 tiny) +---0.06 MB (00.21%) -- property-tables Some of the trees in this section measure things that do not cross-cut the measurements in the "explicit" tree, such as those in the "preference-service" example above. Finally, at the end of this section are individual measurements, as the following example shows. ...
Hacking Tips
that last (failed) run under gdb. rr with reftest To break on the write of a differing pixel: Find the X/Y of a pixel that differs Use 'run Z' where Z is the mark in the log for TEST-START. For example in '[rr 28496 607198]REFTEST TEST-START | file:///home/bgirard/mozilla-central/tree/image/test/reftest/bmp/bmpsuite/b/wrapper.html?badpalettesize.bmp' Z would be 607198. ...
Web Replay
urrently these only happen when graphics updates are performed, at which point there is no JS on the stack). There is a new onPopFrame handler, which is needed when doing reverse-step-in operations. Operations on the debuggee which require interaction with the system will fail. These operations may be property accesses, evals, or object calls, and an example is accessing the font property of a CanvasRenderingContext2D. Failed operations currently just produce a placeholder "INCOMPLETE" result. Operations on the debuggee which have side effects -- eval("x.f = 3") -- should be avoided. When the process resumes forward or backward these side effects will be lost (the process reverts to its original state) and while paused at a breakpoint these effects can cause some strange behavior -- after ...
Gecko Roles
rop-down list icon directly adjacent to the button. ROLE_IPADDRESS Represents an edit control designed for an Internet Protocol (IP) address. The edit control is divided into sections for the different parts of the IP address. ROLE_ACCEL_LABEL Represents a label control that has an accelerator. ROLE_ARROW Represents an arrow in one of the four cardinal directions. ROLE_CANVAS Represents a control that can be drawn into and is used to trap events. ROLE_CHECK_MENU_ITEM Represents a menu item with a check box. ROLE_COLOR_CHOOSER Represents a specialized dialog that lets the user choose a color. ROLE_DATE_EDITOR Represents control whose purpose is to allow a user to edit a date. ROLE_DESKTOP_ICON An iconified internal frame in an ROLE_D...
Index
Mozilla › Tech › XPCOM › Index
nce Called to cancel a pending asynchronous DNS request. The listener will passed to asyncResolve will be notified immediately with a status code of NS_ERROR_ABORT. 468 nsIDNSService Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API Reference, XPCOM Interface Reference Implemented by: @mozilla.org/network/dns-service;1. To access the service, use: 469 nsIDOMCanvasRenderingContext2D Interfaces, Interfaces:Scriptable, XPCOM Interface Reference The nsIDOMCanvasRenderingContext2D interface implements the DOM CanvasRenderingContext2D interface. See that page for details. 470 nsIDOMChromeWindow DOM, Interfaces, Interfaces:Scriptable, XPCOM, XPCOM API Reference, XPCOM Interface Reference On some operating systems, we must allow the ...
nsIAccessibleRole
hat has a drop-down list icon directly adjacent to the button. ROLE_IPADDRESS 63 Represents an edit control designed for an Internet Protocol (IP) address. The edit control is divided into sections for the different parts of the IP address. ROLE_ACCEL_LABEL 64 Represents a label control that has an accelerator. ROLE_ARROW 65 Represents an arrow in one of the four cardinal directions. ROLE_CANVAS 66 Represents a control that can be drawn into and is used to trap events. It is used for html:canvas. ROLE_CHECK_MENU_ITEM 67 Represents a menu item with a check box. ROLE_COLOR_CHOOSER 68 Represents a specialized dialog that lets the user choose a color. ROLE_DATE_EDITOR 69 Represents control whose purpose is to allow a user to edit a date. ROLE_DESKTOP_ICON 70 An iconified internal fra...
nsIDOMFileReader
1 / Fennec 1.0) Inherits from: nsISupports Implemented by: @mozilla.org/files/filereader;1. ...
nsIDragService
location within the image. If aImage is null, aImageX and aImageY are not used and the image is instead determined from the source node aDOMNode, and the offset calculated so that the initial location for the image appears in the same screen position as where the element is located. The node must be within a document. Currently, supported images are all DOM nodes. If this is an HTML <image> or <canvas> element, the drag image is taken from the image data. If the element is in a document, it will be rendered at its displayed size, otherwise, it will be rendered at its real size. For other types of elements, the element is rendered into an offscreen buffer in the same manner as it is currently displayed. The document selection is hidden while drawing. The aDragEvent must be supplied as the curre...
nsIScriptError
ategories the Web Console does not display "XPConnect JavaScript" "component javascript" "chrome javascript" "chrome registration" "XBL" "XBL Prototype Handler" "XBL Content Sink" "xbl javascript" "FrameConstructor" Categories the Web Console displays "HUDConsole" "CSS Parser" "CSS Loader" "content javascript" "DOM Events" "DOM:HTML" "DOM Window" "SVG" "ImageMap" "HTML" "Canvas" "DOM3 Load" "DOM" "malformed-xml" "DOM Worker javascript" "Mixed Content Blocker" "CSP" "Invalid HSTS Headers" "Insecure Password Field" See also Using the Web Console Error Console nsIConsoleMessage nsIScriptError2 ...
XPCOM Interface Reference
rollersnsIConverterInputStreamnsIConverterOutputStreamnsICookiensICookie2nsICookieAcceptDialognsICookieConsentnsICookieManagernsICookieManager2nsICookiePermissionnsICookiePromptServicensICookieServicensICookieStoragensICrashReporternsICryptoHMACnsICryptoHashnsICurrentCharsetListenernsICycleCollectorListenernsIDBChangeListenernsIDBFolderInfonsIDNSListenernsIDNSRecordnsIDNSRequestnsIDNSServicensIDOMCanvasRenderingContext2DnsIDOMChromeWindownsIDOMClientRectnsIDOMDesktopNotificationnsIDOMDesktopNotificationCenternsIDOMElementnsIDOMEventnsIDOMEventGroupnsIDOMEventListenernsIDOMEventTargetnsIDOMFilensIDOMFileErrornsIDOMFileExceptionnsIDOMFileListnsIDOMFileReadernsIDOMFontFacensIDOMFontFaceListnsIDOMGeoGeolocationnsIDOMGeoPositionnsIDOMGeoPositionAddressnsIDOMGeoPositionCallbacknsIDOMGeoPositionCoordsn...
Deprecated tools - Firefox Developer Tools
d to support application development for Firefox OS. Alternatives Remote debugging is available in about:debugging as of Firefox 68. Features not ported to about:debugging are: WiFi debugging for Firefox for Android, application development. Features that are planned but not ported yet: remote browser screenshots and edit remote browser configuration. More details on the mailing-list thread. Canvas debugger Bugzilla issue: bug 1403938 Removed as of Firefox 67 Description Canvas Debugger allowed users to inspect the canvas element and see how frequently a given function is called. It was deprecated due to lack of use. We do not have dedicated documentation for the Canvas Debugger. Alternatives Spector.js is a WebExtension that can provide these features with 3D contexts. Web Audio ...
CSS Painting API - Web APIs
that responds to computed style changes. To find out more about how this is used, consult Using the CSS Painting API. Interfaces PaintWorklet Programmatically generates an image where a CSS property expects a file. Access this interface through CSS.paintWorklet. PaintWorkletGlobalScope The global execution context of the paintWorklet. PaintRenderingContext2D Implements a subset of the CanvasRenderingContext2D API. It has an output bitmap that is the size of the object it is rendering to. PaintSize Returns the read-only values of the output bitmap's width and height. Dictionaries PaintRenderingContext2DSettings A dictionary providing a subset of CanvasRenderingContext2D settings. Examples To draw directly into an element's background using JavaScript in our CSS, we define...
Clipboard.write() - Web APIs
Web › API › Clipboard › write
lipboardItem object into which the text will be placed for sending to the clipboard. The key of the object passed to the ClipboardItem constructor indicates the content type, the value indicates the content. The content could be a text or even a Blob (e.g. for copying images to the clipboard). Then write() is called, specifying both a fulfilment function and an error function. Example of copying canvas contents to the clipboard function copyCanvasContentsToClipboard(canvas, onDone, onError) { canvas.toBlob(function (blob) { let data = [new ClipboardItem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { onDone(); }, function (err) { onError(err); }) }); } Note: You can only pass in one clipboard item at a time. Specifications ...
DOMRect - Web APIs
Web › API › DOMRect
It inherits from its parent, DOMRectReadOnly. ...
DataTransfer.setDragImage() - Web APIs
generated from the drag target (the element the dragstart event is fired at), and follows the mouse pointer during the drag. This image is created automatically, so you do not need to create it yourself. However, if a custom image is desired, the DataTransfer.setDragImage() method can be used to set the custom image to be used. The image will typically be an <image> element but it can also be a <canvas> or any other visible element. The method's x and y coordinates define how the image should appear relative to the mouse pointer. These coordinates define the offset into the image where the mouse cursor should be. For instance, to display the image so that the pointer is at its center, use values that are half the width and height of the image. This method must be called in the dragstart event...
EXT_float_blend - Web APIs
s will no longer result in an INVALID_OPERATION error. Usage notes On devices that support the EXT_float_blend extension, it is automatically, implicitly, enabled when any one or more of EXT_color_buffer_float, OES_texture_float, or WEBGL_color_buffer_float are enabled. This ensures that content written before EXT_float_blend was exposed by WebGL will function as expected. ...
Using files from web applications - Web APIs
xhr = new XMLHttpRequest(); this.xhr = xhr; const self = this; this.xhr.upload.addEventListener("progress", function(e) { if (e.lengthComputable) { const percentage = Math.round((e.loaded * 100) / e.total); self.ctrl.update(percentage); } }, false); xhr.upload.addEventListener("load", function(e){ self.ctrl.update(100); const canvas = self.ctrl.ctx.canvas; canvas.parentNode.removeChild(canvas); }, false); xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php"); xhr.overrideMimeType('text/plain; charset=x-user-defined-binary'); reader.onload = function(evt) { xhr.send(evt.target.result); }; reader.readAsBinaryString(file); } The FileUpload() function show...
File - Web APIs
Web › API › File
A File object is a specific kind of a Blob, and can be used in any context that a Blob can. ...
FileReader - Web APIs
s web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement. Important note: FileReader is used to read file content from the user's (remote) system in secure ways only. It cannot be used to simply read a file by pathname from a file system. To read files by pathname in JavaScript, standard Ajax solutions should be used to do server-side file reading, with CORS permission if reading cross-domain. Note: This feature is available in Web Workers. ...
Using the Gamepad API - Web APIs
The Gamepad API is a way for developers and designers to access and use gamepads and other game controllers. The Gamepad API introduces new events on the Window object for reading gamepad and controller (hereby referred to as gamepad) state. ...
HTMLElement.hidden - Web APIs
den property applies to all presentation modes and should not be used to hide content that is meant to be directly accessible to the user. Appropriate use cases for hidden include: Content that isn't yet relevant but may be needed later Content that was previously needed but is not any longer Content that is reused by other parts of the page in a template-like fashion Creating an offscreen canvas as a drawing buffer Inappropriate use cases include: Hiding panels in a tabbed dialog box Hiding content in one presentation while intending it to be visible in others Elements that are not hidden must not link to elements which are. Syntax isHidden = HTMLElement.hidden; HTMLElement.hidden = true | false; Value A Boolean which is true if the element is hidden from view; otherwise,...
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
youtOptimalForPlayback: DOMString; Value Boolean value set to true indicates that video is being rendered optimally (better performance and using less battery power). If false, improvements can be made to optimize performance. For msIsLayoutOptimalForPlayback to be true, avoid the following: Video elements with Cascading Style Sheets (CSS) outlines set. Rendering a video element through a canvas element. Embedding video elements in a Scalable Vector Graphics (SVG). You can listen to the onMSVideoOptimalLayoutChanged event to be notified when the msIsLayoutOptimalForPlayback property changes. *To enable Stereo 3D playback, msIsLayoutOptimalForPlayback must be true. See also HTMLVideoElement Microsoft API extensions ...
ImageBitmap.close() - Web APIs
Web › API › ImageBitmap › close
some drawing using the gl context ... ...
ImageBitmap - Web APIs
It can be created from a variety of source objects using the createImageBitmap() factory method. ImageBitmap provides an asynchronous and resource efficient pathway to prepare textures for rendering in WebGL. Properties ImageBitmap.height Read only Is an unsigned long representing the height, in CSS pixels, of the ImageData. ImageBitmap.width Read only Is an unsigned long representing the width, in CSS pixels, of the ImageData. Methods ImageBitmap.close() Disposes of all graphical resources associated with an ImageBitmap. ...
ImageData - Web APIs
Web › API › ImageData
Constructors ImageData() Creates an ImageData object from a given Uint8ClampedArray and the size of the image it contains. If no array is given, it creates an image of a transparent black rectangle. Note that this is the most common way to create such an object in workers as createImageData() is not available there. ...
MediaRecorder() - Web APIs
ific media container (file type), and, further, can specify the exact codec and codec configuration(s) to use by specifying the codecs parameter. Syntax var mediaRecorder = new MediaRecorder(stream[, options]); Parameters stream The MediaStream that will be recorded. This source media can come from a stream created using navigator.mediaDevices.getUserMedia() or from an <audio>, <video> or <canvas> element. options Optional A dictionary object that can contain the following properties: mimeType: A MIME type specifying the format for the resulting media; you may simply specify the container format (the browser will select its preferred codecs for audio and/or video), or you may use the codecs parameter and/or the profiles parameter to provide detailed information about which co...
MediaStream - Web APIs
ediaStream interface represents a stream of media content. A stream consists of several tracks such as video or audio tracks. Each track is specified as an instance of MediaStreamTrack.You can obtain a MediaStream object either by using the constructor or by calling MediaDevices.getUserMedia(). Some user agents subclass this interface to provide more precise information or functionality, like in CanvasCaptureMediaStream. Constructor MediaStream() Creates and returns a new MediaStream object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of MediaStreamTrack objects). Properties This interface inherits properties from its parent, EventTarget. MediaStream.active Read only A B...
MediaStream Recording API - Web APIs
at any time by calling MediaRecorder.stop(). Note: Individual Blobs containing slices of the recorded media will not necessarily be individually playable. The media needs to be reassembled before playback. If anything goes wrong during recording, an error event is sent to the MediaRecorder. You can listen for error events by setting up a onerror event handler. Example here, we use an HTML Canvas as source of the MediaStream, and stop recording after 9 seconds. var canvas = document.querySelector("canvas"); // Optional frames per second argument. var stream = canvas.captureStream(25); var recordedChunks = []; console.log(stream); var options = { mimeType: "video/webm; codecs=vp9" }; mediaRecorder = new MediaRecorder(stream, options); mediaRecorder.ondataavailable = handleDataAvailable...
Media Capture and Streams API (Media Stream) - Web APIs
urceNode. The output of the MediaStream object is linked to a consumer. It can be a media elements, like <audio> or <video>, the WebRTC RTCPeerConnection API or a Web Audio API MediaStreamAudioSourceNode. Interfaces In these reference articles, you'll find the fundamental information you'll need to know about each of the interfaces that make up the Media Capture and Streams API. ...
Node.cloneNode() - Web APIs
Web › API › Node › cloneNode
s defaulted instead of a deep clone. Example let p = document.getElementById("para1") let p_prime = p.cloneNode(true) Notes Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction). Additionally, for a <canvas> element, the painted image is not copied. Warning: cloneNode() may lead to duplicate element IDs in a document! If the original node has an id attribute, and the clone will be placed in the same document, then you should modify the clone's ID to be unique. Name attributes may need to be modified also, depending on whether duplicate names are expected. To clone a node to insert into a diffe...
OVR_multiview2 - Web APIs
onsidered incomplete. Calling checkFramebufferStatus for a framebuffer in this state returns FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR. Methods framebufferTextureMultiviewOVR() Simultaneously renders to multiple elements of a 2D texture array. Examples This example is taken from the specification. See also this three.js demo for a live multiview example. ...
PaintWorklet.registerPaint - Web APIs
le worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorklet. The file itself is loaded through CSS.paintWorklet.addModule() (documented here on the parent class of PaintWorklet, at Worklet.addModule(). ...
PaintWorklet - Web APIs
ntWorklet. Examples The following three examples go together to show creating, loading, and using a PaintWorklet. Create a PaintWorklet The following shows an example worklet module. This should be in a separate js file. Note that registerPaint() is called without a reference to PaintWorklet. ...
Path2D - Web APIs
Web › API › Path2D
Constructors Path2D() Path2D constructor. Creates a new Path2D object. Methods Path2D.addPath() Adds a path to the current path. Path2D.closePath() Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing. ...
TextMetrics.actualBoundingBoxAscent - Web APIs
The read-only actualBoundingBoxAscent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the top of the bounding rectangle used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxAscent; // 8; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxAscent' in that specification. ...
TextMetrics.actualBoundingBoxDescent - Web APIs
The read-only actualBoundingBoxDescent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxDescent; // 0; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxDescent' in that specification. ...
TextMetrics.actualBoundingBoxLeft - Web APIs
The read-only actualBoundingBoxLeft property of the TextMetrics interface is a double giving the distance parallel to the baseline from the alignment point given by the CanvasRenderingContext2D.textAlign property to the left side of the bounding rectangle of the given text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxLeft; // 0; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxLeft' in that specification. ...
TextMetrics.actualBoundingBoxRight - Web APIs
The read-only actualBoundingBoxRight property of the TextMetrics interface is a double giving the distance parallel to the baseline from the alignment point given by the CanvasRenderingContext2D.textAlign property to the right side of the bounding rectangle of the given text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.actualBoundingBoxRight; // 15.633333333333333; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.actualBoundingBoxRight' in that specification. ...
TextMetrics.alphabeticBaseline - Web APIs
The read-only alphabeticBaseline property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the alphabetic baseline of the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.alphabeticBaseline; // -0; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.alphabeticBaseline' in that specification. ...
TextMetrics.emHeightAscent - Web APIs
The read-only emHeightAscent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the top of the em square in the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.emHeightAscent; // 7.59765625; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.emHeightAscent' in that specification. ...
TextMetrics.emHeightDescent - Web APIs
The read-only emHeightDescent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the bottom of the em square in the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.emHeightDescent; // -2.40234375; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.emHeightDescent' in that specification. ...
TextMetrics.fontBoundingBoxAscent - Web APIs
The read-only fontBoundingBoxAscent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the top of the highest bounding rectangle of all the fonts used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.fontBoundingBoxAscent; // 10; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.fontBoundingBoxAscent' in that specification. ...
TextMetrics.fontBoundingBoxDescent - Web APIs
The read-only fontBoundingBoxDescent property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline attribute to the bottom of the bounding rectangle of all the fonts used to render the text, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.fontBoundingBoxDescent; // 3; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.fontBoundingBoxDescent' in that specification. ...
TextMetrics.hangingBaseline - Web APIs
The read-only hangingBaseline property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the hanging baseline of the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.hangingBaseline; // 6.078125; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.hangingBaseline' in that specification. ...
TextMetrics.ideographicBaseline - Web APIs
The read-only ideographicBaseline property of the TextMetrics interface is a double giving the distance from the horizontal line indicated by the CanvasRenderingContext2D.textBaseline property to the ideographic baseline of the line box, in CSS pixels. Examples const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const text = ctx.measureText('foo'); // returns TextMetrics object text.ideographicBaseline; // -1.201171875; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.ideographicBaseline' in that specification. ...
TextMetrics.width - Web APIs
Web › API › TextMetrics › width
The read-only width property of the TextMetrics interface contains the text's advance width (the width of that inline box) in CSS pixels. Examples Given this <canvas> element: <canvas id="canvas"></canvas> ... you can get a TextMetrics object using the following code: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let text = ctx.measureText('foo'); // TextMetrics object text.width; // 16; Specifications Specification HTML Living StandardThe definition of 'TextMetrics.width' in that specification. ...
Transferable - Web APIs
c conditions, such as being transfered to a Worker using the Worker.postMessage() method. Note: The Transferable interface technically no longer exists. The functionality of Transferable objects still exists, however, but is implemented at a more fundamental level (technically speaking, using the [Transferable] WebIDL extended attribute). The ArrayBuffer, MessagePort, ImageBitmap and OffscreenCanvas types implement this interface. Properties The Transferable interface does not implement or inherit specific properties. Methods The Transferable interface does not implement or inherit specific properties. Specifications Specification Status Comment HTML Living StandardThe definition of 'Transferable' in that specification. Living Standard Replaced Transfe...
WEBGL_lose_context.loseContext() - Web APIs
bGL API and allows you to simulate losing the context of a WebGLRenderingContext context. It triggers the steps described in the WebGL specification for handling context lost. The context will remain lost until WEBGL_lose_context.restoreContext() is called. Syntax gl.getExtension('WEBGL_lose_context').loseContext(); Examples With this method, you can simulate the webglcontextlost event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_l...
WEBGL_lose_context.restoreContext() - Web APIs
The WEBGL_lose_context.restoreContext() method is part of the WebGL API and allows you to simulate restoring the context of a WebGLRenderingContext object. Syntax gl.getExtension('WEBGL_lose_context').restoreContext(); Errors thrown INVALID_OPERATION if the context was not lost. Examples With this method, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_lose_context.loseContext' in that specification. Recommendation Initial definition. ...
WEBGL_lose_context - Web APIs
formation, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Methods WEBGL_lose_context.loseContext() Simulates losing the context. WEBGL_lose_context.restoreContext() Simulates restoring the context. Examples With this extension, you can simulate the webglcontextlost and webglcontextrestored events: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WEBGL_lose_contextThe definition of 'WEBGL_los...
WebGL2RenderingContext.blitFramebuffer() - Web APIs
destination rectangle. mask A GLbitfield specifying a bitwise OR mask indicating which buffers are to be copied. Possible values: gl.COLOR_BUFFER_BIT gl.DEPTH_BUFFER_BIT gl.STENCIL_BUFFER_BIT filter A GLenum specifying the interpolation to be applied if the image is stretched. Possible values: gl.NEAREST gl.LINEAR Return value None. Examples gl.blitFramebuffer(0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height, gl.COLOR_BUFFER_BIT, gl.NEAREST); Specifications Specification Status Comment WebGL 2.0The definition of 'blitFramebuffer' in that specification. Editor's Draft Initial definition for WebGL. OpenGL ES 3.0The definition of 'glBlitFramebuffer' in that specificatio...
WebGLBuffer - Web APIs
ebGLBuffer object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLBuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindBuffer() WebGLRenderingContext.createBuffer() WebGLRenderingContext.deleteBuffer() WebGLRenderingContext.isBuffer() Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLBuffer' in that specification. Recommendation Initial definition. ...
WebGLContextEvent.statusMessage - Web APIs
The read-only WebGLContextEvent.statusMessage property contains additional event status information, or is an empty string if no additional information is available. Examples The statusMessage property can contain a platform dependent string with details of an event. This can occur, for example, if the webglcontextcreationerror event is fired. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextcreationerror', function(e) { console.log('WebGL context creation failed:' + e.statusMessage || 'Unknown error'); }, false); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEvent.statusMessage' in that specification. Recommendation Initial definiti...
WebGLContextEvent - Web APIs
erties from its parent interface, Event. WebGLContextEvent.statusMessage A read-only property containing additional information about the event. Methods This interface doesn't define any own methods, but inherits methods from its parent interface, Event. Examples With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost and webglcontextrestored events: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').loseContext(); // WebGLContextEvent event with type "webglcontextlost" is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLContextEven...
WebGLFramebuffer - Web APIs
ne any methods or properties of its own and its content is not directly accessible. When working with WebGLFramebuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindFramebuffer() WebGLRenderingContext.createFramebuffer() WebGLRenderingContext.deleteFramebuffer() WebGLRenderingContext.isFramebuffer() Examples Creating a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createFramebuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLFramebuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderbuffer - Web APIs
methods or properties of its own and its content is not directly accessible. When working with WebGLRenderbuffer objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindRenderbuffer() WebGLRenderingContext.createRenderbuffer() WebGLRenderingContext.deleteRenderbuffer() WebGLRenderingContext.isRenderbuffer() Examples Creating a render buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createRenderbuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderbuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.bindBuffer() - Web APIs
ven WebGLBuffer. An attempt to bind the buffer to another target will throw an INVALID_OPERATION error and the current buffer binding will remain the same. A WebGLBuffer which has been marked for deletion with deleteBuffer cannot be (re-)bound. An attempt to do so will generate an INVALID_OPERATION error, and the current binding will remain untouched. Examples Binding a buffer to a target var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); Getting current bindings To check the current buffer bindings, query the ARRAY_BUFFER_BINDING and ELEMENT_ARRAY_BUFFER_BINDING constants. gl.getParameter(gl.ARRAY_BUFFER_BINDING); gl.getParameter(gl.ELEMENT_ARRAY_BUFFER_BINDING); Specifications ...
WebGLRenderingContext.bindFramebuffer() - Web APIs
BUFFER. Used as a destination for drawing, rendering, clearing, and writing operations. gl.READ_FRAMEBUFFER: Used as a source for reading operations. framebuffer A WebGLFramebuffer object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.FRAMEBUFFER, gl.DRAW_FRAMEBUFFER, or gl.READ_FRAMEBUFFER. Examples Binding a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); Getting current bindings To check the current frame buffer binding, query the FRAMEBUFFER_BINDING constant. gl.getParameter(gl.FRAMEBUFFER_BINDING); Specifications Specification Status Comment WebGL 1.0...
WebGLRenderingContext.bindRenderbuffer() - Web APIs
arget, renderbuffer); Parameters target A GLenum specifying the binding point (target). Possible values: gl.RENDERBUFFER: Buffer data storage for single images in a renderable internal format. renderbuffer A WebGLRenderbuffer object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.RENDERBUFFER. Examples Binding a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer); Getting current bindings To check the current renderbuffer binding, query the RENDERBUFFER_BINDING constant. gl.getParameter(gl.RENDERBUFFER_BINDING); Specifications Specification Status Comment We...
WebGLRenderingContext.bindTexture() - Web APIs
llowing values are available additionally: gl.TEXTURE_3D: A three-dimensional texture. gl.TEXTURE_2D_ARRAY: A two-dimensional array texture. texture A WebGLTexture object to bind. Return value None. Exceptions A gl.INVALID_ENUM error is thrown if target is not gl.TEXTURE_2D, gl.TEXTURE_CUBE_MAP, gl.TEXTURE_3D, or gl.TEXTURE_2D_ARRAY. Examples Binding a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); Getting current bindings To check the current texture binding, query the gl.TEXTURE_BINDING_2D or gl.TEXTURE_BINDING_CUBE_MAP constants. gl.getParameter(gl.TEXTURE_BINDING_2D); Specifications Specification Status Comment ...
WebGLRenderingContext.bufferData() - Web APIs
where to start reading the buffer. length Optional A GLuint defaulting to 0. Return value None. Exceptions A gl.OUT_OF_MEMORY error is thrown if the context is unable to create a data store with the given size. A gl.INVALID_VALUE error is thrown if size is negative. A gl.INVALID_ENUM error is thrown if target or usage are not one of the allowed enums. Examples Using bufferData var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); Getting buffer information To check the current buffer usage and buffer size, use the WebGLRenderingContext.getBufferParameter() method. gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_SIZE); gl...
WebGLRenderingContext.bufferSubData() - Web APIs
srcOffset A GLuint specifying the element index offset where to start reading the buffer. length Optional A GLuint defaulting to 0. Return value None. Exceptions A gl.INVALID_VALUE error is thrown if the data would be written past the end of the buffer or if data is null. A gl.INVALID_ENUM error is thrown if target is not one of the allowed enums. Examples Using bufferSubData var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, 1024, gl.STATIC_DRAW); gl.bufferSubData(gl.ARRAY_BUFFER, 512, data); Specifications Specification Status Comment WebGL 1.0The definition of 'bufferSubData' in that specification. Recommendatio...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
ed images are a mix of renderbuffers and textures. When using the OVR_multiview2 extension, the following value can be returned additionally: ext.FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: If baseViewIndex is not the same for all framebuffer attachment points where the value of FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is not NONE, the framebuffer is considered incomplete. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.checkFramebufferStatus(gl.FRAMEBUFFER); Specifications Specification Status Comment WebGL 1.0The definition of 'checkFramebufferStatus' in that specification. Recommendation Initial definition for WebGL. OpenGL ES 2.0The definiti...
WebGLRenderingContext.commit() - Web APIs
The WebGLRenderingContext.commit() method pushes frames back to the original HTMLCanvasElement, if the context is not directly fixed to a specific canvas. Syntax void WebGLRenderingContext.commit() Examples var htmlCanvas = document.createElement('canvas'); var offscreen = htmlCanvas.transferControlToOffscreen(); var gl = offscreen.getContext('webgl'); // ... some drawing using the gl context ... // Push frames back to the original HTMLCanvasElement gl.commit(); Specifications Specification Status Comment HTML Living StandardThe definition of 'the commit() method of the OffscreenCanvas object's rendering context' in that specification. Living Standard ...
WebGLRenderingContext.createBuffer() - Web APIs
The WebGLRenderingContext.createBuffer() method of the WebGL API creates and initializes a WebGLBuffer storing data such as vertices or colors. Syntax WebGLBuffer gl.createBuffer(); Parameters None. Return value A WebGLBuffer storing data such as vertices or colors. Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenBuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createFramebuffer() - Web APIs
The WebGLRenderingContext.createFramebuffer() method of the WebGL API creates and initializes a WebGLFramebuffer object. Syntax WebGLFramebuffer gl.createFramebuffer(); Parameters None. Return value A WebGLFramebuffer object. Examples Creating a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenFramebuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.createRenderbuffer() - Web APIs
The WebGLRenderingContext.createRenderbuffer() method of the WebGL API creates and initializes a WebGLRenderbuffer object. Syntax WebGLRenderbuffer gl.createRenderbuffer(); Parameters None. Return value A WebGLRenderbuffer object that stores data such an image, or can be source or target of an rendering operation. Examples Creating a render buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderBuffer = gl.createRenderBuffer(); Specifications Specification Status Comment WebGL 1.0The definition of 'createRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenRenderbuffers' in that specification. Standard Man page of the (similar) OpenGL A...
WebGLRenderingContext.createTexture() - Web APIs
The WebGLRenderingContext.createTexture() method of the WebGL API creates and initializes a WebGLTexture object. Syntax WebGLTexture gl.createTexture(); Parameters None. Return value A WebGLTexture object to which images can be bound to. Examples See also the WebGL tutorial on Using textures in WebGL. Creating a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); Specifications Specification Status Comment WebGL 1.0The definition of 'createTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glGenTextures' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteBuffer() - Web APIs
The WebGLRenderingContext.deleteBuffer() method of the WebGL API deletes a given WebGLBuffer. This method has no effect if the buffer has already been deleted. Syntax void gl.deleteBuffer(buffer); Parameters buffer A WebGLBuffer object to delete. Return value None. Examples Deleting a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); // ... gl.deleteBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteBuffers' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteFramebuffer() - Web APIs
The WebGLRenderingContext.deleteFramebuffer() method of the WebGL API deletes a given WebGLFramebuffer object. This method has no effect if the frame buffer has already been deleted. Syntax void gl.deleteFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer object to delete. Return value None. Examples Deleting a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); // ... gl.deleteFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteFramebuffers' in that specification. Standard...
WebGLRenderingContext.deleteProgram() - Web APIs
The WebGLRenderingContext.deleteProgram() method of the WebGL API deletes a given WebGLProgram object. This method has no effect if the program has already been deleted. Syntax void gl.deleteProgram(program); Parameters program A WebGLProgram object to delete. Return value None. Examples Deleting a program var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.deleteProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteProgram' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteProgram' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.deleteRenderbuffer() - Web APIs
The WebGLRenderingContext.deleteRenderbuffer() method of the WebGL API deletes a given WebGLRenderbuffer object. This method has no effect if the render buffer has already been deleted. Syntax void gl.deleteRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer object to delete. Return value None. Examples Deleting a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); // ... gl.deleteRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteRenderbuffers' in that specification...
WebGLRenderingContext.deleteTexture() - Web APIs
The WebGLRenderingContext.deleteTexture() method of the WebGL API deletes a given WebGLTexture object. This method has no effect if the texture has already been deleted. Syntax void gl.deleteTexture(texture); Parameters texture A WebGLTexture object to delete. Return value None. Examples Deleting a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); // ... gl.deleteTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'deleteTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDeleteTextures' in that specification. Standard Man page of the (similar) OpenGL API. ...
WebGLRenderingContext.drawingBufferHeight - Web APIs
The read-only WebGLRenderingContext.drawingBufferHeight property represents the actual height of the current drawing buffer. It should match the height attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested height. Syntax gl.drawingBufferHeight; Examples Given this <canvas> element: <canvas id="canvas"></canvas> You can get the height of the drawing buffer with the following lines: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.drawingBufferHeight; // 150 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.drawingBufferHeight' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.drawingBufferWidth - Web APIs
The read-only WebGLRenderingContext.drawingBufferWidth property represents the actual width of the current drawing buffer. It should match the width attribute of the <canvas> element associated with this context, but might differ if the implementation is not able to provide the requested width. Syntax gl.drawingBufferWidth; Examples Given this <canvas> element: <canvas id="canvas"></canvas> You can get the width of the drawing buffer with the following lines: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.drawingBufferWidth; // 300 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLRenderingContext.drawingBufferWidth' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.getExtension() - Web APIs
tension(name); Parameters name A String for the name of the WebGL extension to enable. Return value A WebGL extension object, or null if name does not match (case-insensitive) to one of the strings in WebGLRenderingContext.getSupportedExtensions. Examples Once a WebGL extension is enabled, you are able to use the methods, properties or constants that this extension object provides. var canvas = document.getElementById('canvas'); gl = canvas.getContext('webgl'); gl.getExtension('WEBGL_lose_context').loseContext(); WebGL extensions Extensions for the WebGL API are registered in the WebGL Extension Registry. The current extensions are: ANGLE_instanced_arrays EXT_blend_minmax EXT_color_buffer_float EXT_color_buffer_half_float EXT_disjoint_timer_query EXT_float_blend EXT_fr...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
_FLOAT, gl.LOW_INT, gl.MEDIUM_INT, or gl.HIGH_INT. Return value A WebGLShaderPrecisionFormat object or null, if an error occurs. Exceptions gl.INVALID_ENUM if the shader or precision types aren't recognized. gl.INVALID_OPERATION if the shader compiler isn't supported. Examples The following code gets the precision format of a gl.VERTEX_SHADER with a gl.MEDIUM_FLOAT precision type. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } Specifications Specification Status Comment WebGL 1.0The definition of 'getShaderPrecisionFormat' in that specification. Recommendation Initial defin...
WebGLRenderingContext.isBuffer() - Web APIs
The WebGLRenderingContext.isBuffer() method of the WebGL API returns true if the passed WebGLBuffer is valid and false otherwise. Syntax GLboolean gl.isBuffer(buffer); Parameters buffer A WebGLBuffer to check. Return value A GLboolean indicating whether or not the buffer is valid. Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.isBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isBuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsBuffer' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isFramebuffer() - Web APIs
The WebGLRenderingContext.isFramebuffer() method of the WebGL API returns true if the passed WebGLFramebuffer is valid and false otherwise. Syntax GLboolean gl.isFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer to check. Return value A GLboolean indicating whether or not the frame buffer is valid. Examples Checking a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.isFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isFramebuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsFramebuffer' in that specification. Standard Man pag...
WebGLRenderingContext.isProgram() - Web APIs
The WebGLRenderingContext.isProgram() method of the WebGL API returns true if the passed WebGLProgram is valid, false otherwise. Syntax GLboolean gl.isProgram(program); Parameters program A WebGLProgram to check. Return value A GLboolean indicating whether or not the program is valid. Examples Checking a program var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.isProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'isProgram' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsProgram' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
The WebGLRenderingContext.isRenderbuffer() method of the WebGL API returns true if the passed WebGLRenderbuffer is valid and false otherwise. Syntax GLboolean gl.isRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer to check. Return value A GLboolean indicating whether or not the renderbuffer is valid. Examples Checking a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.isRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isRenderbuffer' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsRenderbuffer' in that specification. Standar...
WebGLRenderingContext.isShader() - Web APIs
The WebGLRenderingContext.isShader() method of the WebGL API returns true if the passed WebGLShader is valid, false otherwise. Syntax GLboolean gl.isShader(shader); Parameters shader A WebGLShader to check. Return value A GLboolean indicating whether or not the shader is valid. Examples Checking a shader var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var shader = gl.createShader(gl.VERTEX_SHADER); // ... gl.isShader(shader); Specifications Specification Status Comment WebGL 1.0The definition of 'isShader' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsShader' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.isTexture() - Web APIs
The WebGLRenderingContext.isTexture() method of the WebGL API returns true if the passed WebGLTexture is valid and false otherwise. Syntax GLboolean gl.isTexture(texture); Parameters texture A WebGLTexture to check. Return value A GLboolean indicating whether or not the texture is valid. Examples Checking a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.isTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'isTexture' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glIsTexture' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.scissor() - Web APIs
ing to a specified rectangle. Syntax void gl.scissor(x, y, width, height); Parameters x A GLint specifying the horizontal coordinate for the lower left corner of the box. Default value: 0. y A GLint specifying the vertical coordinate for the lower left corner of the box. Default value: 0. width A non-negative Glsizei specifying the width of the scissor box. Default value: width of the canvas. height A non-negative Glsizei specifying the height of the scissor box. Default value: height of the canvas. Return value None. Exceptions If either width or height is a negative value, a gl.INVALID_VALUE error is thrown. Examples When the scissor test is enabled, only pixels within the scissor box can be modified by drawing commands. // turn on scissor test gl.enable(gl.SCISSOR_TEST);...
WebGLShaderPrecisionFormat.precision - Web APIs
The read-only WebGLShaderPrecisionFormat.precision property returns the number of bits of precision that can be represented. For integer formats this value is always 0. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision; // 23 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).precision; // 0 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.precision' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat.rangeMax - Web APIs
The read-only WebGLShaderPrecisionFormat.rangeMax property returns the base 2 log of the absolute value of the maximum value that can be represented. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMax; // 127 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMax; // 24 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.rangeMax' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat.rangeMin - Web APIs
The read-only WebGLShaderPrecisionFormat.rangeMin property returns the base 2 log of the absolute value of the minimum value that can be represented. Examples var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).rangeMin; // 127 gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT).rangeMin; // 24 Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat.rangeMin' in that specification. Recommendation Initial definition. ...
WebGLShaderPrecisionFormat - Web APIs
PrecisionFormat.rangeMax Read only The base 2 log of the absolute value of the maximum value that can be represented. WebGLShaderPrecisionFormat.precision Read only The number of bits of precision that can be represented. For integer formats this value is always 0. Examples A WebGLShaderPrecisionFormat object is returned by the WebGLRenderingContext.getShaderPrecisionFormat() method. var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); // WebGLShaderPrecisionFormat { rangeMin: 127, rangeMax: 127, precision: 23 } Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLShaderPrecisionFormat' in that specification. Recommendation Initial defi...
WebGLTexture - Web APIs
ture object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLTexture objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.bindTexture() WebGLRenderingContext.createTexture() WebGLRenderingContext.deleteTexture() WebGLRenderingContext.isTexture() Examples Creating a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLTexture' in that specification. Recommendation Initial definition. ...
WebGLUniformLocation - Web APIs
in a shader program. Description The WebGLUniformLocation object does not define any methods or properties of its own and its content is not directly accessible. When working with WebGLUniformLocation objects, the following methods of the WebGLRenderingContext are useful: WebGLRenderingContext.getUniformLocation() WebGLRenderingContext.uniform() Examples Getting an uniform location var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var location = gl.getUniformLocation(WebGLProgram, 'uniformName'); Specifications Specification Status Comment WebGL 1.0The definition of 'WebGLUniformLocation' in that specification. Recommendation Initial definition. ...
WebGL by example - Web APIs
random color when the user clicks. Simple color animation A very basic color animation, done by clearing the WebGL drawing buffer with a different random color every second. Color masking Modifying random colors by applying color masking and thus limiting the range of displayed colors to specific shades. Basic scissoring How to draw simple rectangles and squares with scissoring operations. Canvas size and WebGL The example explores the effect of setting (or not setting) the canvas size to its element size in CSS pixels, as it appears in the browser window. Boilerplate 1 The example describes repeated pieces of code that will be hidden from now on, as well as defining a JavaScript utility function to make WebGL initialization easier. Scissor animation Some animation fun with scissorin...
Animating textures in WebGL - Web APIs
This example uses the glMatrix library to perform its matrix and vertex math. You'll need to include it if you create your own project based on this code. ...
Using textures in WebGL - Web APIs
to test and deploy your code. For local testing, see our guide How do you set up a local testing server? for help. See this hacks.mozilla.org article for an explanation of how to use CORS-approved images as WebGL textures, with a self-contained example. Note: CORS support for WebGL textures and the crossOrigin attribute for image elements is implemented in Gecko 8.0. Tainted (write-only) 2D canvases can't be used as WebGL textures. A 2D <canvas> becomes tainted, for example, when a cross-domain image is drawn on it. Note: CORS support for Canvas 2D drawImage is implemented in Gecko 9.0. This means that using a cross-domain image with CORS approval does no longer taint the 2D canvas, so the 2D canvas remains usable as the source of a WebGL texture. Note: CORS support for cross-domain v...
Fundamentals of WebXR - Web APIs
he logic yourself. They're designed for creating and animating 3D scenes regardless of context. A-Frame (specifically designed for creating WebXR-based apps) Babylon.js Three.js Game toolkits The game toolkits are designed for game developers and often include gaming-specific features such as physics models, input control systems, asset management, 3D sound playback, and the like. PlayCanvas Next steps With these basic facts in hand, you're ready to take those next steps into the world of mixed reality. The following articles can help. WebXR application life cycle Starting up and shutting down a WebXR session Movement, orientation, and motion: A WebXR example ...
Inputs and input sources - Web APIs
ct() function is assumed to be one which knows how to return the object held in the specified hand to its initial position, as it was recorded by pickUpObject() in the squeezestart event handler. Transient actions If an XR device uses the mouse to simulate a controller when in the inline mode, the approximate sequence of things takes place: The user presses the mouse button while inside the <canvas> presenting the WebXR scene. The mouse event is captured by the XR device's driver. The device creates a new XRInputSource to represent the simulated XR input source. The targetRayMode is set to screen, and the other information is filled out as appropriate. This new input source is temporarily added to the list that's returned by the XRSession property inputSources. The browser delivers point...
Rendering and the WebXR frame animation callback - Web APIs
he last time the screen refreshed, the browser will call your frame renderer callback every time it's ready to repaint your app or site window. In this context, "repaint" simply means the process of ensuring that the screen's displayed content matches what the DOM and the elements within are trying to present at the moment. Hardare vertical refresh rate When the browser is ready to refresh the <canvas> within which your WebXR content is displayed, it calls your frame rendering callback, which uses the specified timestamp and any other relevant data, such as models and textures, as well as application state, to render the scene--as it should appear at the specified time--into the WebGL backbuffer. When your callback returns, the browser transfers that backbuffer to the display or XR device, alo...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
on and orientation of a point and by extension the entire object for which that point is the origin. While this is a little heavy-handed to be used for every single object in a scene, it can be very useful for a few specific objects to have their own coordinate system in this manner. The world space; the origin of this space is the origin of the WebGL coordinate system underlying the entire 3D canvas. The player, avatar, or camera; the origin of this space is used as the camera position for rendering the scene to be displayed to the user. The hand and/or hand controller; each of these represents one of the user's hands, either in the form of the hand itself or a controller (or both). The origin is generally the center of the user's fisted hand. The target ray; each controller or other hand...
Basic concepts behind Web Audio API - Web APIs
al, audio visualizations are achieved by accessing an output of audio data over time, usually gain or frequency data, and then using a graphical technology to turn that into a visual output, such as a graph. The Web Audio API has an AnalyserNode available that doesn't alter the audio signal passing through it. Instead it outputs audio data that can be passed to a visualization technology such as <canvas>. You can grab data using the following methods: AnalyserNode.getFloatFrequencyData() Copies the current frequency data into a Float32Array array passed into it. AnalyserNode.getByteFrequencyData() Copies the current frequency data into a Uint8Array (unsigned byte array) passed into it. AnalyserNode.getFloatTimeDomainData() Copies the current waveform, or time-domain, data into a...
Using the Web Audio API - Web APIs
Your use case will determine what tools you use to implement audio. ...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
around by right-clicking and moving the mouse to change the viewing angle. First, we add an event handler for mousemove events, which calls our code to perform the rotation if the right mouse button is down. Note also that we set oncontextmenu up to be ignored by calling preventDefault() on those events. This prevents the right-clicks from causing the context menu from appearing in the browser. canvas.oncontextmenu = (event) => { event.preventDefault(); }; canvas.addEventListener("mousemove", (event) => { if (event.buttons & 2) { rotateViewBy(event.movementX, event.movementY); } }); Next, the rotateViewBy() function, which updates the mouse look direction's yaw and pitch based on the mouse delta values from the mousemove event. The pitch is restricted so that you can't look beyond st...
XRRenderState.baseLayer - Web APIs
x var xrWebGLLayer = xrRenderState.baseLayer; Value A XRWebGLLayer object which is used as the source of the world's contents when rendering each frame of the scene. See the examples below to see how to use updateRenderState() to set the current XRWebGLLayer used for rendering the scene. Examples You can set the XRWebGLLayer used for rendering by calling updateRenderState(), like this: let canvas = document.querySelector("canvas"); gl = canvas.getContext("webgl", { xrCompatible: true }); setNewWebGLLayer(); function setNewWebGLLayer(gl) { if (!gl) { /* WebGL not available */ return; } xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl); }); }; Here, the canvas obtained in the first line is the canvas into which WebGL is going to draw. That cont...
XRRenderStateInit - Web APIs
o be the near clip plane. No part of the scene on the viewer's side of this plane will be rendered. This is 0.1 meters (10 centimeters) by default. inlineVerticalFieldOfView Optional A floating-point value indicating the default field of view, in radians, to be used when computing the projection matrix for an inline XRSession. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property must not be specified for immersive sessions, so the value is null by default for immersive sessions. The default value is otherwise ? * 0.5 (half of the value of pi). Usage notes Any properties not specified in the XRRenderStateInit compliant object passed into updateRenderState() are left at their current values. Specifications Specification Status...
XRView.transform - Web APIs
Web › API › XRView › transform
he left eye and one for the right, but there may be only one if in monoscopic mode. Currently, WebXR doesn't support more than two views per pose, although room has been left to extend the specification to support that in the future with some additions to the API. For each view, we obtain its viewport and pass that to WebGL using gl.viewport(). For the left eye, this will be the left half of the canvas, while the right eye will use the right half. Then we iterate over each object that makes up the scene. Each object's model view matrix is computed by multiplying its own matrix which describes the object's own position and orientation by the additional position and orientation adjustments needed to match the camera's movement. To convert the "camera focused" transform matrix into an "object foc...
Text labels and names - Accessibility
tribute to the document's title.) Some screen readers replace the contents of the title attribute with the contents of the enclosed document's <title>. It's safest and most accessible to provide the same title in both places. Content with images must be labeled Provide descriptive text for all contentful (that is, non-decorative) images and image-like elements. This includes SVG images, <img>, <canvas>, <map>, and <area> elements, as well as <input> elements where type=image and <object> elements where the type starts with image/. The typical way to do this is with the alt attribute. Be sure that the description conveys what is shown in the image. Example <img src="milkweed.jgp" alt="Black and white close-up photo of milkweed flowers"> Interactive elements must be labeled If an eleme...
zoom - CSS: Cascading Style Sheets
Web › CSS › @viewport › zoom
a document defined by the @viewport at-rule. A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values are zoomed in. Smaller values are zoomed out. Syntax /* Keyword value */ zoom: auto; /* <number> values */ zoom: 0.8; zoom: 2.0; /* <percentage> values */ zoom: 150%; Values auto The user agent will set the document's initial zoom factor. The user agent may use the size of canvas area on which the document is rendered to determine that factor. <number> A non-negative number used as the zoom factor. <percentage> A non-negative percentage value used as the zoom factor. Formal definition Related at-rule@viewportInitial valueautoPercentagesthe zoom factor itselfComputed valueauto, or a non-negative number or percentage as specified Formal syntax auto | <number> | <pe...
Replaced elements - CSS: Cascading Style Sheets
e on a replaced element is that there are properties which support controlling the positioning of the element's content within its box. See Controlling object position within the content box for further information. Replaced elements Typical replaced elements are: <iframe> <video> <embed> <img> Some elements are treated as replaced elements only in specific cases: <option> <audio> <canvas> <object> <applet> HTML spec also says that an <input> element can be replaced, because <input> elements of the "image" type are replaced elements similar to <img>. However, other form controls, including other types of <input> elements, are explicitly listed as non-replaced elements (the spec describes their default platform-specific rendering with the term "Widgets"). Objects inserted usin...
Visual formatting model - CSS: Cascading Style Sheets
different types, which affect their visual formatting. The type of the box generated depends on the value of the CSS display property. Initially defined in CSS2, the display property is extended in the CSS Display Module Level 3. In addition, some of the terminologies around the display have been updated and clarified in the years since CSS2. CSS takes your source document and renders it onto a canvas. To do this, it generates an intermediary structure, the box tree, which represents the formatting structure of the rendered document. Each box in the box tree represents its corresponding element (or pseudo-element) in space and/or time on the canvas, while each text run in the box tree likewise represents the contents of its corresponding text nodes. Then, for each element, CSS generates zero ...
background-clip - CSS: Cascading Style Sheets
round-color is transparent, user agents must instead propagate the computed values of the background properties from that element's first HTML <body> child element. The used values of that <body> element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the <body> element rather than the HTML element. Syntax /* Keyword values */ background-clip: border-box; background-clip: padding-box; background-clip: content-box; background-clip: text; /* Global values */ background-clip: inherit; background-clip: initial; background-clip: unset; Values border-box The background extends to the outside edge of the border (but underneat...
element() - CSS: Cascading Style Sheets
Web › CSS › element
The element() CSS function defines an <image> value generated from an arbitrary HTML element. This image is live, meaning that if the HTML element is changed, the CSS properties using the resulting value are automatically updated. A particularly useful scenario for using this would be to render an image in an HTML <canvas> element, then use that as a background. On Gecko browsers, you can use the non-standard document.mozSetImageElement() method to change the element being used as the background for a given CSS background element. Syntax element(id) where: id The ID of an element to use as the background, specified using the HTML attribute #id on the element. Examples These examples can be viewed live in builds of Firefox that support -moz-element(). A somewhat realistic ...
image-rendering - CSS: Cascading Style Sheets
values respectively. Formal definition Initial valueautoApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax auto | crisp-edges | pixelated Examples Setting image scaling algorithms In practical use, the pixelated and crisp-edges rules can be combined to provide some fallback for each other. (Just prepend the actual rules with the fallback.) The Canvas API can provide a fallback solution for pixelated through manual image data manipulation or with imageSmoothingEnabled. <div> <img class="auto" alt="auto" src="https://udn.realityripple.com/samples/de/cedd397be3.jpg" /> <img class="pixelated" alt="pixelated" src="https://udn.realityripple.com/samples/de/cedd397be3.jpg" /> <img class="crisp-edges" alt="crisp-edges" src="https://udn.reality...
offset-path - CSS: Cascading Style Sheets
rder-box | padding-box | content-box Examples Animating an element with offset-path The offset-path properties in the CSS code sample defines a motion path that is identical to the <path> element in the SVG. The path, as can be seen in the rendering of the SVG code, is a line drawing of a house with a chimney. SVG The top and bottom halves of the scissors would appear in the top left of the canvas were they not positioned along the starting point of the motion path defined by offset-path. <svg xmlns="http://www.w3.org/2000/svg" width="700" height="450" viewBox="350 0 1400 900"> <title>House and Scissors</title> <rect x="595" y="423" width="610" height="377" fill="blue" /> <polygon points="506,423 900,190 1294,423" fill="yello...
paint() - CSS: Cascading Style Sheets
Web › CSS › paint
support NoSamsung Internet Android Full support 9.2Legend Full support Full support No support No support See also PaintWorklet CSS Painting API Using the CSS Painting API <image> canvas ...
transform-box - CSS: Cascading Style Sheets
5)" /> <rect id="box" x="10" y="10" width="10" height="10" rx="1" ry="1" stroke="black" fill="none" /> </g> </svg> In the CSS we have an animation that uses a transform to rotate the rectangle infinitely. transform-box: fill-box is used to make the the transform-origin the center of the bounding box, so the rectangle spins in place. Without it, the transform origin is the center of the SVG canvas, and so you get a very different effect. svg{ width:80vh; border:1px solid #d9d9d9; position:absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; } #box{ transform-origin:50% 50%; /*+++++++++++++++++++++++++++*/ /* if I remove this rule the pen won't work properly on Chrome for Mac, FF, Safari Will still work properly on Chrome for PC & Opera*/ transform-box: ...
Ajax - Developer guides
Web › Guide › AJAX
ts web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement. HTML in XMLHttpRequest The XMLHttpRequest specification adds HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest. View All... Tools axios Promise based HTTP client, which uses XMLHttpRequest internally. See also Ajax: A New Approach to Web Applicati...
Guide to Web APIs - Developer guides
Web › Guide › API
ingly more powerful and capable applications, running either on the web, locally, or through technology such as Node.js, on a server. On this page you'll find a complete list of all of the APIs provided by the full web technology stack. ...
Graphics on the Web - Developer guides
Websites and applications often need to present graphics, such as images. Static images can easily be displayed using the <img> element, or by setting the background of HTML elements using the background-image property. You can also construct graphics on-the-fly, or manipulate images after the fact. These articles provide insight into how you can accomplish this. 2D Graphics Canvas The <canvas> element provides APIs to draw 2D graphics using JavaScript. SVG Scalable Vector Graphics (SVG) lets you use lines, curves, and other geometric shapes to render graphics. With vectors, you can create images that scale cleanly to any size. View All... 3D Graphics WebGL A guide to getting started with WebGL, the 3D graphics API for the Web. This technology lets you use standard Open...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
the manipulation of new multimedia content. WebRTC This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application. Track and WebVTT The <track> element allows subtitles and chapters. WebVTT is a text track format. 2D/3D graphics AND effects Canvas tutorial Learn about the new <canvas> element and how to draw graphs and other objects in Firefox. HTML5 Text API for <canvas> elements The HTML5 text API is now supported by <canvas> elements. WebGL WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 <canvas> elements. SVG An XML-based format of vectorial images that c...
Developer guides
les to adaptive live streams. This article is intended as a starting point for exploring the various delivery mechanisms of web-based media and compatibility with popular browsers. Audio and video manipulation The beauty of the web is that you can combine technologies to create new forms. Having native audio and video in the browser means we can use these data streams with technologies such as <canvas>, WebGL or Web Audio API to modify audio and video directly, for example adding reverb/compression effects to audio, or grayscale/sepia filters to video. This article provides a reference to explain what you need to do. Events developer guide Events refer to two things: a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page; and the na...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border. Other ways to use color CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color. The HTML Canvas API Lets you draw 2D bitmapped graphics in a <canvas> element. See our Canvas tutorial to learn more. SVG (Scalable Vector Graphics) Lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image. SVG commands are formatted as XML, and can be embedded directly into a web page or can be placed in he page using the <img> element, just like any other type o...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
script <script> elements, Worker importScripts style <link rel=stylesheet> elements, CSS @import track <track> elements video <video> elements worker Worker, SharedWorker crossorigin This enumerated attribute indicates whether CORS must be used when fetching the resource. CORS-enabled images can be reused in the <canvas> element without being tainted. The allowed values are: anonymous A cross-origin request (i.e. with an Origin HTTP header) is performed, but no credential is sent (i.e. no cookie, X.509 certificate, or HTTP Basic authentication). If the server does not give credentials to the origin site (by not setting the Access-Control-Allow-Origin HTTP header) the resource will be tainted and its usage ...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
enarios. <source> The HTML <source> element specifies multiple media resources for the <picture>, the <audio> element, or the <video> element. Scripting In order to create dynamic content and Web applications, HTML supports the use of scripting languages, most prominently JavaScript. Certain elements support this capability. Element Description <canvas> Use the HTML <canvas> element with either the canvas scripting API or the WebGL API to draw graphics and animations. <noscript> The HTML <noscript> element defines a section of HTML to be inserted if a script type on the page is unsupported or if scripting is currently turned off in the browser. <script> The HTML <script> element is used to embed executable code or...
hidden - HTML: Hypertext Markup Language
levant, then there is no reason to link to it. It would be fine, however, to use the ARIA aria-describedby attribute to refer to descriptions that are themselves hidden. While hiding the descriptions implies that they are not useful on their own, they could be written in such a way that they are useful in the specific context of being referenced from the element that they describe. Similarly, a canvas element with the hidden attribute could be used by a scripted graphics engine as an off-screen buffer, and a form control could refer to a hidden form element using its form attribute. Note: Changing the value of the CSS display property on an element with the hidden attribute overrides the behavior. For instance, elements styled display: flex will be displayed despite the hidden attribute's pr...
Inline elements - HTML: Hypertext Markup Language
nts, on the other hand, typically cause a line break to occur (although, as usual, this can be changed using CSS). ...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
e type of resource in the as attribute. A simple example might look like this (see our JS and CSS example source, and also live): <head> <meta charset="utf-8"> <title>JS and CSS preload example</title> <link rel="preload" href="style.css" as="style"> <link rel="preload" href="main.js" as="script"> <link rel="stylesheet" href="style.css"> </head> <body> <h1>bouncing balls</h1> <canvas></canvas> <script src="main.js" defer></script> </body> Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on. This example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly ...
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
CORS? This cross-origin sharing standard can enable cross-site HTTP requests for: Invocations of the XMLHttpRequest or Fetch APIs, as discussed above. Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so. WebGL textures. Images/video frames drawn to a canvas using drawImage(). CSS Shapes from images. This article is a general discussion of Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers. Functional overview The Cross-Origin Resource Sharing standard works by adding new HTTP headers that let servers describe which origins are permitted to read that information from a web browser. Additionally, for HTTP reques...
HTTP Index - HTTP
Web › HTTP › Index
s succeeded, but that the client doesn't need to go away from its current page. A 204 response is cacheable by default. An ETag header is included in such a response. 226 205 Reset Content HTTP, HTTP Status Code, Reference, Status code The HTTP 205 Reset Content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the UI. 227 206 Partial Content HTTP, HTTP Status, Range Requests, Success The HTTP 206 Partial Content success status response code indicates that the request has succeeded and has the body contains the requested ranges of data, as described in the Range header of the request. 228 300 Multiple Choices HTTP, HTTP Status Code, Reference, Sta...
205 Reset Content - HTTP
Web › HTTP › Status › 205
The HTTP 205 Reset Content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the UI. Status 205 Reset Content Specifications Specification Title RFC 7231, section 6.3.6: 205 Reset Content Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content Compatibility Notes Browser behavior differs if this response erroneously includes a body on persistent connections See 204 No Content for more detail. ...
Indexed collections - JavaScript
which represents the buffer in a specific format, and use that to read and write the contents of the buffer. Typed array views Typed array views have self descriptive names and provide views for all the usual numeric types like Int8, Uint32, Float64 and so forth. There is one special typed array view, {jsxref("Uint8ClampedArray")}}, which clamps the values between 0 and 255. This is useful for Canvas data processing, for example. Type Value Range Size in bytes Description Web IDL type Equivalent C type Int8Array -128 to 127 1 8-bit two's complement signed integer byte int8_t Uint8Array 0 to 255 1 8-bit unsigned integer octet uint8_t Uint8ClampedArray 0 to 255 1 8-bit unsigned integer (clamped) oc...
JavaScript technologies overview - JavaScript
e other DOM elements? Read the DOM documentation. Other notable APIs The setTimeout and setInterval functions were first specified on the Window interface in HTML Standard. XMLHttpRequest makes it possible to send asynchronous HTTP requests. The CSS Object Model abstract CSS rules as objects. WebWorkers allows parallel computation. WebSockets allows low-level bidirectional communication. Canvas 2D Context is a drawing API for <canvas>. ...
SharedArrayBuffer - JavaScript
from the beginning. Examples Creating a new SharedArrayBuffer var sab = new SharedArrayBuffer(1024); Slicing the SharedArrayBuffer sab.slice(); // SharedArrayBuffer { byteLength: 1024 } sab.slice(2); // SharedArrayBuffer { byteLength: 1022 } sab.slice(-2); // SharedArrayBuffer { byteLength: 2 } sab.slice(0, 1); // SharedArrayBuffer { byteLength: 1 } Using it in a WebGL buffer const canvas = document.querySelector('canvas'); const gl = canvas.getContext('webgl'); const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, sab, gl.STATIC_DRAW); Specifications Specification ECMAScript (ECMA-262)The definition of 'SharedArrayBuffer' in that specification. ...
JavaScript typed arrays - JavaScript
r a DataView which represents the buffer in a specific format, and use that to read and write the contents of the buffer. Typed array views Typed array views have self-descriptive names and provide views for all the usual numeric types like Int8, Uint32, Float64 and so forth. There is one special typed array view, the Uint8ClampedArray. It clamps the values between 0 and 255. This is useful for Canvas data processing, for example. Type Value Range Size in bytes Description Web IDL type Equivalent C type Int8Array -128 to 127 1 8-bit two's complement signed integer byte int8_t Uint8Array 0 to 255 1 8-bit unsigned integer octet uint8_t Uint8ClampedArray 0 to 255 1 8-bit unsigned integer (clamped) oc...
CSS and JavaScript animation performance - Web Performance
es an efficient way to make animations in JavaScript. The callback function of the method is called by the browser before the next repaint on each frame. Compared to setTimeout()/setInterval(), which need a specific delay parameter, requestAnimationFrame() is much more efficient. Developers can create an animation by simply changing an element's style each time the loop is called (or updating the Canvas draw, or whatever.) Note: Like CSS transitions and animations, requestAnimationFrame() pauses when the current tab is pushed into the background. For more details read animating with JavaScript from setinterval to requestAnimationFrame. Performance comparison: transitions vs. requestAnimationFrame The fact is that, in most cases, the performance of CSS-based animations is almost the same a...
Populating the page: how browsers work - Web Performance
t, the drawing to the screen is generally broken down into several layers. If this occurs, then compositing is necessary. Painting can break the elements in the layout tree into layers. Promoting content into layers on the GPU (instead of the main thread on the CPU) improves paint and repaint performance. There are specific properties and elements that instantiate a layer, including <video> and <canvas>, and any element which has the CSS properties of opacity, a 3D transform, will-change, and a few others. These nodes will be painted onto their own layer, along with their descendants, unless a descendant necessitates its own layer for one (or more) of the above reasons. Layers do improve performance, but are expensive when it comes to memory management, so should not be overused as part of web...
Web Performance
perience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. There are tools, APIs, and best practices that help us measure and improve web performance. We cover them in this section: Key performance guides Animation performance and frame rateAnimation on the web can be done via SVG, JavaScript, including <canvas> and WebGL, CSS animation, <video>, animated gifs and even animated PNGs and other image types. The performance cost of animating a CSS property can vary from one property to another, and animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate.Critical rendering pathThe Critical Rendering Path is the sequence of steps the browser goes through to c...
The building blocks of responsive design - Progressive web apps (PWAs)
size your containers and text, not fixed widths such as pixels. This has a lot of advantages in that the layout will adapt to different viewport dimensions. Let's look at an example. We've written a simple-but-fun prototype for an application called Snapshot, which takes a video stream from your webcam (using getUserMedia()) then allows you to capture stills from that video stream (using HTML5 <canvas>), and save them to a gallery. You can then view previously-captured images and delete them. Other articles will discuss the functionality in more detail, but here we're interested in the layout. Note: You can find the Snapshot app on Github; check out the code and help improve it. You can also see Snapshot running live. Note that getUserMedia() is an experimental technology, which currently on...
display - SVG: Scalable Vector Graphics
Web › SVG › Attribute › display
The geometry of a graphics element with display set to none is not included in bounding box and clipping paths calculations. The display attribute only affects the direct rendering of a given element, whereas it does not prevent elements from being referenced by other elements. For example, setting it to none on a <path> element will prevent that element from getting rendered directly onto the canvas, but the <path> element can still be referenced by a <textPath> element; furthermore, its geometry will be used in text-on-a-path processing even if the <path> has a display value of none. This attribute also affects direct rendering into offscreen canvases, such as occurs with masks or clip paths. Thus, setting display="none" on a child of a <mask> will prevent the given child element from bein...
opacity - SVG: Scalable Vector Graphics
Web › SVG › Attribute › opacity
ute specifies the transparency of an object or of a group of objects, that is, the degree to which the background behind the element is overlaid. Note: As a presentation attribute, opacity can be used as a CSS property. See the css opacity property for more information. ...
systemLanguage - SVG: Scalable Vector Graphics
The systemLanguage attribute represents a list of supported language tags. This list is matched against the language defined in the user preferences. 35 elements are using this attribute: <a>, <altGlyph>, <animate>, <animateColor>, <animateMotion>, <animateTransform>, <audio>, <canvas>, <circle>, <clipPath>, <cursor>, <defs>, <discard>, <ellipse>, <foreignObject>, <g>, <iframe>, <image>, <line>, <mask>, <path>, <pattern>, <polygon>, <polyline>, <rect>, <set>, <svg>, <switch>, <text>, <textPath>, <tref>, <tspan>, <unknown>, <use>, and <video> Usage notes Value <language-tags> Default value None Animatable No <language-tags> The value is a set of comma-separated tokens, each of which must be a Language-Tag value, as defined in BCP 47. systemLangu...
visibility - SVG: Scalable Vector Graphics
bute pointer-events, graphics elements which have their visibility attribute set to hidden still might receive events. Note: As a presentation attribute, visibility can be used as a CSS property. See the css visibility property for more information. ...
<tref> - SVG: Scalable Vector Graphics
Web › SVG › Element › tref
Recommendation Initial definition ...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
pans Implementation status unknown Offset distances of text positioned along a transformed path measured in text elements coordinate system Implementation status unknown Embedded Content Change Notes <video> Implementation status unknown <audio> Implementation status unknown <iframe> Implementation status unknown <canvas> Implementation status unknown <source> Implementation status unknown <track> Implementation status unknown Painting Change Notes paint-order Implemented (bug 828805) will-change instead of buffered-rendering Implementation status unknown context-fill and context-stroke paint values Implemented (bug 719286 (Fir...
SVG as an Image - SVG: Scalable Vector Graphics
SVG images can be used as an image format, in a number of contexts. Many browsers support SVG images in: HTML <img> or <svg> elements CSS background-image Gecko-specific contexts Additionally, Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) introduced support for using SVG in these contexts: CSS list-style-image CSS content SVG <image> element SVG <feImage> element Canvas drawImage function Restrictions For security purposes, Gecko places some restrictions on SVG content when it's being used as an image: JavaScript is disabled. External resources (e.g. images, stylesheets) cannot be loaded, though they can be used if inlined through data: URIs. :visited-link styles aren't rendered. Platform-native widget styling (based on OS theme) is disabled. Note that ...
Clipping and masking - SVG: Scalable Vector Graphics
<clipPath id="cut-off-bottom"> <rect x="0" y="0" width="200" height="100" /> </clipPath> </defs> <circle cx="100" cy="100" r="100" clip-path="url(#cut-off-bottom)" /> </svg> Centered at (100,100) a circle with radius 100 is painted. The attribute clip-path references a <clipPath> element with a single rect element. This rectangular on its own would paint the upper half of the canvas black. Note, that the clipPath element is usually placed in a defs section. The rect will not be painted, however. Instead its pixel data will be used to determine, which pixels of the circle "make it" to the final rendering. Since the rectangle covers only the upper half of the circle, the lower half of the circle will vanish: ScreenshotLive sample We now have a semicircle without having to d...
Paths - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Paths
75 80 Z" fill="red"/> <path d="M 80 230 A 45 45, 0, 0, 1, 125 275 L 125 230 Z" fill="purple"/> <path d="M 230 230 A 45 45, 0, 1, 1, 275 275 L 275 230 Z" fill="blue"/> </svg> Arcs are an easy way to create pieces of circles or ellipses in drawings. For instance, a pie chart would require a different arc for each piece. If transitioning to SVG from <canvas>, arcs can be the hardest thing to learn, but are also much more powerful. Complete circles and ellipses are the only shapes that SVG arcs have trouble drawing. Because the start and end points for any path going around a circle are the same point, there are an infinite number of circles that could be chosen, and the actual path is undefined. It's possible to approximate them by making the start ...
Tools for SVG - SVG: Scalable Vector Graphics
rts the newest SVG features like masking, clipping, patterns, full gradients, groups. It does not support the older browsers that Raphael does. Google Docs URL: www.google.com/google-d-s/drawings/ Drawings from Google Docs can be exported as SVG. Science The well-known plotting tools xfig and gnuplot both support exporting as SVG. To render graphs on the web JSXGraph supports VML, SVG and canvas, automatically deciding which technology to use based on browser capabilities. In GIS (Geographic Information System) applications SVG is often used as both storage and rendering format. See carto.net for details. More tools! The W3C offers a list of programs that support SVG. << Previous ...
SVG: Scalable Vector Graphics
Web › SVG
e Details about the SVG DOM API, for interaction with JavaScript. Applying SVG effects to HTML content SVG works together with HTML, CSS and JavaScript. Use SVG to enhance a regular HTML page or web application. View All... Community View Mozilla forums... Mailing list Newsgroup RSS feed Tools SVG Test Suite Markup Validator More Tools... Other resources: XML, CSS, DOM, Canvas Examples Google Maps (route overlay) & Docs (spreadsheet charting) SVG bubble menus SVG authoring guidelines An overview of the Mozilla SVG Project Frequently asked questions regarding SVG and Mozilla SVG as an image SVG animation with SMIL SVG art gallery Animation and interactions Like HTML, SVG has a document model (DOM) and events, and is accessible from JavaScript. This allo...
Tutorials
nges to CSS properties, instead of having the changes take effect instantly. Quick Guide to Implement Web Fonts (with @font-face) The @font-face feature from CSS3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way. Starting to Write CSS An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS. Canvas tutorial Learn how to draw graphics using scripting using the canvas element. HTML5 Doctor Articles about using HTML5 right now. JavaScript Tutorials Introductory level JavaScript first steps In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through...
WebAssembly Concepts - WebAssembly
So part of the glue code is implementing the functionality of each respective library used by the C/C++ code. The glue code also contains the logic for calling the above-mentioned WebAssembly JavaScript APIs to fetch, load and run the .wasm file. The generated HTML document loads the JavaScript glue file and writes stdout to a <textarea>. If the application uses OpenGL, the HTML also contains a <canvas> element that is used as the rendering target. It's very easy to modify the Emscripten output and turn it into whatever web app you require. You can find full documentation on Emscripten at emscripten.org, and a guide to implementing the toolchain and compiling your own C/C++ app across to wasm at Compiling from C/C++ to WebAssembly. Writing WebAssembly directly Do you want to build your own c...