차례
      1. 4.8.11 The canvas element
        1. 4.8.11.1 색상 범위와 수정
        2. 4.8.11.2 canvas 요소에서의 보안

4.8.11 The canvas element

요소가 속하는 범주Categories
플로우 컨텐츠Flow content
구문 컨텐츠Phrasing content
포함된 컨텐츠Embedded content
이 요소가 사용될 수 있는 문맥:Contexts in which this element can be used

포함된 컨텐츠가 올 수 있는 곳

Where embedded content is expected.

이 요소가 포함할 수 있는 것:Content model
투명한 내용Transparent
요소에 사용할 수 있는 속성:Content attributes
전역 속성Global attributes
width
height
DOM interface:
interface HTMLCanvasElement : HTMLElement {
           attribute unsigned long width;
           attribute unsigned long height;
 
  DOMString toDataURL(in optional DOMString type, in any... args);
 
  object getContext(in DOMString contextId, in any... args);
};

canvas 요소는 해상도에 의존하는 비트맵 캔버스와 스크립트를 제공합니다. 이러한 캔버스는 그래프, 게임 그래픽, 기타 비주얼 이미지들을 즉석에서 그려내는 용도로 사용될 수 있습니다.

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, or other visual images on the fly.

좀 더 적절한 요소가 있을 경우 canvas 요소를 문서에 사용하는 것은 피해야 합니다. 예를 들어, canvas 요소를 사용해서 페이지 헤딩을 렌더링하는 것은 적절하지 못합니다: 표현하길 원하는 것이 풍부한 그래픽을 요구한다면, 그러한 것은 적절한 요소(보통, h1)과 함께 CSS스타일시트, 그리고 이를 지원하는 XBL 같은 기술을 이용하여야 합니다.

Authors should not use the canvas element in a document when a more suitable element is available. For example, it is inappropriate to use a canvas element to render a page heading: if the desired presentation of the heading is graphically intense, it should be marked up using appropriate elements (typically h1) and then styled using CSS and supporting technologies such as XBL.

canvas 요소를 사용할 때는, 그 핵심적인 면에서 비트맵 캔버스와 동일한 기능, 또는 목적을 갖는 대체 내용을 함께 제공해야 합니다. 이 컨텐츠는 canvas 요소의 외부에 위치할 수 있습니다. 이러한 컨텐츠가 canvas 요소의 폴백 컨텐츠가 됩니다.

When authors use the canvas element, they must also provide content that, when presented to the user, conveys essentially the same function or purpose as the bitmap canvas. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element's fallback content.

상호작용적인 비주얼 매체에서는, canvas 요소에 대해 스크립트가 허용되고, 또한 canvas 요소가 지원된다면, canvas 요소는 동적으로 생성되는 이미지로 구성된, 포함된 컨텐츠를 나타냅니다.

In interactive visual media, if scripting is enabled for the canvas element, and if support for canvas elements has been enabled, the canvas element represents embedded content consisting of a dynamically created image.

비 상호작용적인, 정적인 비주얼 매체에서는, canvas 요소가 이미 그려졌다면(페이지를 상호작용적인 비주얼 매체를 이용해서 이미 보았고 그것이 현재 출력되고 있는 상황. 또는, 페이지 로딩 과정에서 실행된 스크립트가 요소에서 그러한 그림을 그린 경우), canvas 요소는 현재의 이미지와 사이즈를 갖는 포함된 컨텐츠를 나타냅니다. 그렇지 않다면, 요소는 폴백 컨텐츠를 대신 나타냅니다.

In non-interactive, static, visual media, if the canvas element has been previously painted on (e.g. if the page was viewed in an interactive visual medium and is now being printed, or if some script that ran during the page layout process painted on the element), then the canvas element represents embedded content with the current image and size. Otherwise, the element represents its fallback content instead.

비 시각적 매체, canvas 요소에서 스크립트가 차단된 시각적 매체, 그리고 canvas 요소가 지원되지 않는 경우 요소는 폴백 컨텐츠를 나타냅니다.

In non-visual media, and in visual media if scripting is disabled for the canvas element or if support for canvas elements has been disabled, the canvas element represents its fallback content instead.

canvas 요소가 포함된 컨텐츠를 나타낼 때에도, 사용자는 canvas 요소의 자손 요소(폴백 컨텐츠에 있는)에 포커스를 가질 수 있습니다. 이러한 것을 이용해서 저자들은 키보드로 포커싱할 수 있는 인터랙티브한 캔버스를 만들 수 있습니다. 폴백 컨텐츠 내부에서 포커스를 받을 수 있는 요소들과, (캔버스의..?)인터랙티브한 지역들 간의 1:1 매칭을 갖게 해야 합니다.

When a canvas element represents embedded content, the user can still focus descendants of the canvas element (in the fallback content). This allows authors to make an interactive canvas keyboard-focusable: authors should have a one-to-one mapping of interactive regions to focusable elements in the fallback content.

canvas 요소는 좌표 공간에서의 크기를 조절하기 위한 두가지 속성을 갖습니다. width와 height 입니다. 이러한 속성은, 명시되었다면, 유효한 양의 정수여야 합니다. width 속성의 기본값은 300이고, height 속성의 기본값은 150입니다.

The canvas element has two attributes to control the size of the coordinate space: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

canvas 요소의 원래 크기는 CSS 픽셀로 옮겨진 좌표 공간의 크기와 일치합니다. 그러나, 요소는 스타일시트를 통해 크기의 조절을 할 수 있습니다. 렌더링 과정에서, 이미지는 이러한 레이아웃에 맞도록 크기가 조절됩니다.

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

The size of the coordinate space does not necessarily represent the size of the actual bitmap that the user agent will use internally or during rendering. On high-definition displays, for instance, the user agent may internally use a bitmap with two device pixels per unit in the coordinate space, so that the rendering remains at high quality throughout.

When the canvas element is created, and subsequently whenever the width and height attributes are set (whether to a new value or to the previous value), the bitmap and any associated contexts must be cleared back to their initial state and reinitialized with the newly specified coordinate space dimensions.

When the canvas is initialized, its bitmap must be cleared to transparent black.

The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.

다음의 예제에서는 하나의 사각형이 그려질 것입니다.

Only one square appears to be drawn in the following example:

  // canvas is a reference to a <canvas> element
  var context = canvas.getContext('2d');
  context.fillRect(0,0,50,50);
  canvas.setAttribute('width', '300'); // clears the canvas
  context.fillRect(0,100,50,50);
  canvas.width = canvas.width; // clears the canvas
  context.fillRect(100,0,50,50); // only this square remains

context = canvas . getContext(contextId [, ... ])

캔버스에 그리기 위한 API를 노출하는 객체를 반환합니다.

Returns an object that exposes an API for drawing on the canvas. The first argument specifies the desired API. Subsequent arguments are handled by that API.

현재 정의된 컨텍스트들은 WHATWG 위키 캔버스컨텍스트 페이지에 있습니다.

The list of defined contexts is given on the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

그러한 컨텍스트 ID가 지원되지 않거나, 캔버스가 이미 다른(호환되지 않는) 타입의 컨텍스트로 초기화되었다면 null을 반환합니다(예를 들어, webgl 컨텍스트를 호출한 상태에서 다시 2d 컨텍스트를 호출하는 경우입니다).

Returns null if the given context ID is not supported or if the canvas has already been initialised with some other (incompatible) context type (e.g. trying to get a "2d" context after getting a "webgl" context).

A canvas element can have a primary context, which is the first context to have been obtained for that element. When created, a canvas element must not have a primary context.

The getContext(contextId, args...) method of the canvas element, when invoked, must run the following steps:

  1. Let contextId be the first argument to the method.

  2. If contextId is not the name of a context supported by the user agent, return null and abort these steps.

  3. If the element has a primary context and that context's entry in the WHATWG Wiki CanvasContexts page does not list contextId as a context with which it is compatible, return null and abort these steps. [WHATWGWIKI]

  4. If the element does not have a primary context, let the element's primary context be contextId.

  5. If the getContext() method has already been invoked on this element for the same contextId, return the same object as was returned that time, and abort these steps. The additional arguments are ignored.

  6. Return a new object for contextId, as defined by the specification given for contextId's entry in the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

New context types may be registered in the WHATWG Wiki CanvasContexts page. [WHATWGWIKI]

Anyone is free to edit the WHATWG Wiki CanvasContexts page at any time to add a new context type. These new context types must be specified with the following information:

Keyword

The value of contextID that will return the object for the new API.

Specification

A link to a formal specification of the context type's API. It could be another page on the Wiki, or a link to an external page. If the type does not have a formal specification, an informal description can be substituted until such time as a formal specification is available.

Compatible with

The list of context types that are compatible with this one (i.e. that operate on the same underlying bitmap). This list must be transitive and symmetric; if one context type is defined as compatible with another, then all types it is compatible with must be compatible with all types the other is compatible with.

Vendors may also define experimental contexts using the syntax vendorname-context, for example, moz-3d. Such contexts should be registered in the WHATWG Wiki CanvasContexts page.


url = canvas . toDataURL( [ type, ... ])

캔버스 내부의 이미지에 대해 data:URL 을 반환합니다.

Returns a data: URL for the image in the canvas.

첫번째 매개변수를 제공했다면, 그것은 반환될 이미지의 타입(png 또는 jpeg)를 정합니다. 기본값은 image/png; 이며, 주어진 타입이 지원되지 않는 경우 이 값을 사용합니다. 다른 매개변수는 타입에 종속되며, 이미지가 생성되는 방법을 조절합니다. 그러한 방법은 아래의 테이블에서 주어집니다.

The first argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is image/png; that type is also used if the given type isn't supported. The other arguments are specific to the type, and control the way that the image is generated, as given in the table below.

The toDataURL() method must, when called with no arguments, return a data: URL containing a representation of the image as a PNG file. [PNG] [RFC2397]

If the canvas has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero) then the method must return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)

When the toDataURL(type) method is called with one or more arguments, it must return a data: URL containing a representation of the image in the format given by type. The possible values are MIME types with no parameters, for example image/png, image/jpeg, or even maybe image/svg+xml if the implementation actually keeps enough information to reliably render an SVG image from the canvas.

For image types that do not support an alpha channel, the image must be composited onto a solid black background using the source-over operator, and the resulting image must be the one used to create the data: URL.

Only support for image/png is required. User agents may support other types. If the user agent does not support the requested type, it must return the image using the PNG format.

User agents must convert the provided type to ASCII lowercase before establishing if they support that type and before creating the data: URL.

image/png 이외의 타입을 시도해 보려고 하는 경우, 이미지가 실제로 그러한 타입으로 반환되었는지 확인하기 위해, 반환된 문자열을 살펴볼 수 있습니다. 그러한 문자열이 정확히 "data:image/png," 혹은 "data:image/png;" 로 시작한다면, 이미지는 PNG인 것이며, 다시 말해 시도된 타입은 지원되지 않는 것입니다. (이것의 유일한 예외는 캔버스가 높이, 혹은 너비를 갖지 않는 경우입니다. 이러한 경우에 반환된 문자열은 "data:," 일 것입니다.)

When trying to use types other than image/png, authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".)

If the method is invoked with the first argument giving a type corresponding to one of the types given in the first column of the following table, and the user agent supports that type, then the subsequent arguments, if any, must be treated as described in the second cell of that row.

Type Other arguments
image/jpeg

두번째 매개변수는 0.0 부터 1.0 까지의 값을 가지며, 원하는 품질로 간주됩니다.

The second argument, if it is a number in the range 0.0 to 1.0 inclusive, must be treated as the desired quality level. If it is not a number or is outside that range, the user agent must use its default value, as if the argument had been omitted.

For the purposes of these rules, an argument is considered to be a number if it is converted to an IDL double value by the rules for handling arguments of type any in the Web IDL specification. [WEBIDL]

Other arguments must be ignored and must not cause the user agent to raise an exception. A future version of this specification will probably define other parameters to be passed to toDataURL() to allow authors to more carefully control compression settings, image metadata, etc.

4.8.11.1 색상 범위와 수정

The canvas APIs must perform color correction at only two points: when rendering images with their own gamma correction and color space information onto the canvas, to convert the image to the color space used by the canvas (e.g. using the 2D Context's drawImage() method with an HTMLImageElement object), and when rendering the actual canvas bitmap to the output device.

Thus, in the 2D context, colors used to draw shapes onto the canvas will exactly match colors obtained through the getImageData() method.

The toDataURL() method must not include color space information in the resource returned. Where the output format allows it, the color of pixels in resources created by toDataURL() must match those returned by the getImageData() method.

In user agents that support CSS, the color space used by a canvas element must match the color space used for processing any colors for that element in CSS.

The gamma correction and color space information of images must be handled in such a way that an image rendered directly using an img element would use the same colors as one painted on a canvas element that is then itself rendered. Furthermore, the rendering of images that have no color correction information (such as those returned by the toDataURL() method) must be rendered with no color correction.

Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() method to the canvas, given the appropriate dimensions, has no visible effect.

4.8.11.2 canvas 요소에서의 보안

Information leakage can occur if scripts from one origin can access information (e.g. read pixels) from images from another origin (one that isn't the same).

To mitigate this, canvas elements are defined to have a flag indicating whether they are origin-clean. All canvas elements must start with their origin-clean set to true. The flag must be set to false if any of the following actions occur:

Whenever the toDataURL() method of a canvas element whose origin-clean flag is set to false is called, the method must raise a SECURITY_ERR exception.

Whenever the getImageData() method of the 2D context of a canvas element whose origin-clean flag is set to false is called with otherwise correct arguments, the method must raise a SECURITY_ERR exception.

Even resetting the canvas state by changing its width or height attributes doesn't reset the origin-clean flag.