From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../api/htmlcanvaselement/getcontext/index.html | 292 +++++++++++++++++++++ .../web/api/htmlcanvaselement/height/index.html | 79 ++++++ files/pt-br/web/api/htmlcanvaselement/index.html | 264 +++++++++++++++++++ .../web/api/htmlcanvaselement/todataurl/index.html | 157 +++++++++++ 4 files changed, 792 insertions(+) create mode 100644 files/pt-br/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/height/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/todataurl/index.html (limited to 'files/pt-br/web/api/htmlcanvaselement') diff --git a/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html b/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..c50cd97abb --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,292 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - API + - Canvas + - HTMLCanvasElement + - Referencia + - metodo +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

O metodo HTMLCanvasElement.getContext() retorna um contexto de desenho no canvas, ou {{jsxref("null")}} se o contexto identificado não é suportado.

+ +

Syntax

+ +
canvas.getContext(contextType, contextAttributes);
+
+ +

Parametros

+ +
+
contextType
+
É um {{domxref("DOMString")}} contendo o contexto identificador definindo o contexto de desenho associado ao canvas.        Os valores possiveis são: +
    +
  • "2d", levando a criação de um objeto {{domxref("CanvasRenderingContext2D")}} representando uma  renderização bidimensional.
  • +
  • "webgl" (or "experimental-webgl") que criará um objeto {{domxref("WebGLRenderingContext")}} representando uma renderização tridimensional. Esse contexto está disponivel somente em browsers que implementam WebGL versão 1 (OpenGL ES 2.0).
  • +
  • "webgl2" que criará um objeto {{domxref("WebGL2RenderingContext")}} representando uma renderização tridimensional. Esse contexto está disponivel somente em browsers que implementam WebGL versão 2 (OpenGL ES 3.0). {{experimental_inline}}
  • +
  • "bitmaprenderer" que criará um  {{domxref("ImageBitmapRenderingContext")}} que apenas provê a funcionalidade de substituir o conteúdo do canvas pelo de um {{domxref("ImageBitmap")}}.
  • +
+ +
+

Note: O identificador "experimental-webgl" é usado em novas implementações do WebGL. Essas implementações ou ainda não passaram nos casos de teste, ou os drivers gráficos na plataforma ainda não estão estáveis. O Khronos Group certifica as implementações do WebGL sob certas regas de conformidade.

+
+
+
contextAttributes
+
+

Você pode usar alguns atributos de contexto quando criar o seu contexto de renderização, por exemplo:

+ +
canvas.getContext('webgl',
+                 { antialias: false,
+                   depth: false });
+ Atributos de contexto 2d: + +
    +
  • alpha: Boleano que indica se o canvas contém um canal alfa. Se definido como false, o browser saberá que o resultado será sempre opaco, o que pode acelerar o desenho de conteudo transparente e imagens.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: Boleano que indica quando uma série de operações read-back estão planejadas. Isso forçará o uso de renderização 2D no canvas via software (ao invés de utilizar GPU) o que pode salvar memoria quando {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} for chamado frequentemente. Essa opção está disponivel somente, se a flag gfx.canvas.willReadFrequently.enable está definida como true (o que, por padrão, é o caso do B2G/Firefox OS apenas).
  • +
  • {{non-standard_inline}} (Blink only) storage: String que indica qual storage é usado ("persistent" por padrão).
  • +
+ Atributos de contexto WebGL: + +
    +
  • alpha: Boleano que indica se o canvas contém um buffer alfa.
  • +
  • depth: Boleano que indica que o buffer do desenho tem um buffer de profundidade de pelo menos 16 bits.
  • +
  • stencil: Boleano que indica que o buffer do desenho tem um buffer de stencil de pelo menos 8 bits.
  • +
  • antialias: Boleano que indica se deve realizar o anti-aliasing ou não.
  • +
  • premultipliedAlpha: Boleano que indica se o compositor da página vai assumir que o buffer do desenho contendo cores com alfa pré-multiplicado.
  • +
  • preserveDrawingBuffer: Se o valor é true os buffers não serão limpos e preservarão seus valores até serem limpos ou subrescritos pelo autor.
  • +
  • +

    failIfMajorPerformanceCaveat: Boleano que indica se um contexto será criado se a performance do sistema for baixa.

    +
  • +
+
+
+ +

Return value

+ +

Um {{domxref("RenderingContext")}} que pode ser:

+ + + +

Se o contextType não bater com um possivel contexto de desenho,null é retornado.

+ +

Examples

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

Você pega um contexto 2d do canvas com o código a seguir:

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

Agora você tem contexto de renderização 2d para o canvas e você pode desenhar nele.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde o ultimo snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot do {{SpecName('HTML WHATWG')}} contendo a definição inicial.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2d context){{CompatChrome(4)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatIE(9)}}{{CompatOpera(9)}}{{CompatSafari(3.1)}}
webgl context{{CompatChrome(9)}}[1]
+ {{CompatChrome(33)}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop('1.9.2')}}[1]
+ {{CompatGeckoDesktop('24')}}
11.0[2]9.0[3]5.1[2]
webgl2 context {{CompatChrome(56)}}{{CompatUnknown}}{{CompatGeckoDesktop('25')}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}
2d alpha context attribute32{{CompatUnknown}}{{CompatGeckoDesktop(30)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+

failIfMajorPerformanceCaveat attribute

+
{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
bitmaprenderer context{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2d context){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
webgl2 context {{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
2d alpha context attribute{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(30)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
failIfMajorPerformanceCaveat attribute{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
bitmaprenderer context{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Chrome 9 e Gecko 1.9.2 inicialmente implementaram isso como um experimental-webgl. Desde o Chrome 33 e Gecko 24 é implementado como definido pelo padrão: webgl.

+ +

[2] Internet Explorer 11, WebKit 5.1 e Firefox Mobile implementaram isso como um experimental-webgl.

+ +

[3] Opera 9 implementou isso como um experimental-webgl, ativado nas preferencias do usuario, na versão 15.0 a preferencia de usuario foi removida.

+ +

[4] Gecko 25 implementou isso como um "experimental-webgl2" ativado na preferencia do usuario webgl.enable-prototype-webgl2. Apartir do Gecko 42, a string "webgl2"é usada na mesma configuração e "experimental-webgl2" não é mais aceito.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/height/index.html b/files/pt-br/web/api/htmlcanvaselement/height/index.html new file mode 100644 index 0000000000..fd737da382 --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/height/index.html @@ -0,0 +1,79 @@ +--- +title: HTMLCanvasElement.height +slug: Web/API/HTMLCanvasElement/height +tags: + - API + - Canvas + - HTMLCanvasElement + - Propriedade + - altura +translation_of: Web/API/HTMLCanvasElement/height +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

A propriedade HTMLCanvasElement.height é um inteiro positivo que reflete o atributo {{htmlattrxref("height", "canvas")}} do elemento HTML {{HTMLElement("canvas")}} interpretado em pixels no CSS. Quando o atributo não é especificado, ou se for definido como um valor inválido, como um inteiro negativo, o valor padrão de 150 será usado.

+ +

Essa é uma de duas propriedades, que controla o tamanho do canvas, sendo a outra {{domxref("HTMLCanvasElement.width")}}.

+ +

Sintaxe

+ +
var pxl = canvas.height;
+canvas.height = pxl;
+
+ +

Exemplos

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

Você pode capturar a altura do canvas com o seguinte código:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.height); // 300
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

Compatibilidade entre os browsers

+ + + +

{{Compat("api.HTMLCanvasElement.height")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/index.html b/files/pt-br/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..c2121aab9a --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/index.html @@ -0,0 +1,264 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

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 {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

Inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
Is a positive integer reflecting the {{htmlattrxref("height", "canvas")}} HTML attribute of the {{HTMLElement("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.
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}}
+
Is a {{jsxref("Boolean")}} reflecting the {{htmlattrxref("moz-opaque", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element. 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.
+
{{domxref("HTMLCanvasElement.width")}}
+
Is a positive integer reflecting the {{htmlattrxref("width", "canvas")}} HTML attribute of the {{HTMLElement("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.
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
Is a function that is Initially null, Web content can set this to a JavaScript function that will be called if the page is printed. This function can then redraw the canvas at a higher resolution that is suitable for the printer being used. See this blog post.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
Returns a {{domxref("CanvasCaptureMediaStream")}} that is a real-time video capture of the surface of the canvas.
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a {{domxref("CanvasRenderingContext2D")}} object, whereas calling it with "experimental-webgl" (or "webgl") returns a {{domxref("WebGLRenderingContext")}} object. This context is only available on browsers that implement WebGL.
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi.
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
Creates a {{domxref("Blob")}} object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
Transfers control to an {{domxref("OffscreenCanvas")}} object, either on the main thread or on a worker.
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns a {{domxref("File")}} object representing the image contained in the canvas; this file is a memory-based file, with the specified name. If type is not specified, the image type is image/png.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
{{SpecName('HTML WHATWG', "#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}The method getContext() now returns a {{domxref("RenderingContext")}} rather than an opaque object.
+ The methods probablySupportsContext(), setContext() and transferControlToProxy()have been added.
{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2D context)4.0{{CompatVersionUnknown}}{{CompatGeckoDesktop('1.9.2')}}9.09.0 [1]3.1
toBlob()50{{CompatNo}}{{CompatGeckoDesktop('19')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{obsolete_inline}}
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2D context)2.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}10.0 [1]3.2
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} as experimental-webgl{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
toBlob(){{CompatNo}} (bug 67587)50{{CompatNo}}{{CompatGeckoMobile('18')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{obsolete_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Opera Mini 5.0 and later has partial support.

+ +

[2] Support for the third parameter, has been added in Gecko 25 only: when used with the "image/jpeg" type, this argument specifies the image quality.

+ +

[3] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html b/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..503f9cb636 --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,157 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +tags: + - API + - Canvas + - HTMLCanvasElement + - Imagens +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

O método HTMLCanvasElement.toDataURL() retorna uma data URI, contendo uma representação da imagem no formato especificado pelo parâmetro type (por padrão, esse valor é PNG). A resolução da imagem retornada é de 96 dpi.

+ + + +

Sintaxe

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

Parâmetros

+ +
+
type {{optional_inline}}
+
Uma {{domxref("DOMString")}} indicando o formato da imagem. Por padrão, o formato definido é image/png.
+
encoderOptions {{optional_inline}}
+
Um {{jsxref("Number")}} entre 0 e 1, indicando a qualidade da imagem solicitada pelo tipo image/jpeg ou image/webp.
+ Se esse argumento for outro valor que não de 0 a 1, então o valor padrão (0.92) será usado. Outros valores serão ignorados.
+
+ +

Valor retornado

+ +

Uma {{domxref("DOMString")}} contendo a data URI solicitada.

+ +

Exemplos

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="5" height="5"></canvas>
+
+ +

Você poderá capturar a data-URL do canvas com as seguintes linhas:

+ +
var canvas = document.getElementById('canvas');
+var dataURL = canvas.toDataURL();
+console.log(dataURL);
+// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
+// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
+
+ +

Defindo a qualidade de imagens jpeg

+ +
var fullQuality = canvas.toDataURL('image/jpeg', 1.0);
+// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
+var mediumQuality = canvas.toDataURL('image/jpeg', 0.5);
+var lowQuality = canvas.toDataURL('image/jpeg', 0.1);
+
+ +

Exemplo: Alterando imagens dinamicamente

+ +

Você poderá utilizar esta técnica em associação com os eventos do mouse para alterar dinamicamente uma imagem (escala de cinza vs. cor, neste exemplo):

+ +

HTML

+ +
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
+ +

JavaScript

+ +
window.addEventListener('load', removeColors);
+
+function showColorImg() {
+  this.style.display = 'none';
+  this.nextSibling.style.display = 'inline';
+}
+
+function showGrayImg() {
+  this.previousSibling.style.display = 'inline';
+  this.style.display = 'none';
+}
+
+function removeColors() {
+  var aImages = document.getElementsByClassName('grayscale'),
+      nImgsLen = aImages.length,
+      oCanvas = document.createElement('canvas'),
+      oCtx = oCanvas.getContext('2d');
+  for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
+    oColorImg = aImages[nImgId];
+    nWidth = oColorImg.offsetWidth;
+    nHeight = oColorImg.offsetHeight;
+    oCanvas.width = nWidth;
+    oCanvas.height = nHeight;
+    oCtx.drawImage(oColorImg, 0, 0);
+    oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
+    aPix = oImgData.data;
+    nPixLen = aPix.length;
+    for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
+      aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
+    }
+    oCtx.putImageData(oImgData, 0, 0);
+    oGrayImg = new Image();
+    oGrayImg.src = oCanvas.toDataURL();
+    oGrayImg.onmouseover = showColorImg;
+    oColorImg.onmouseout = showGrayImg;
+    oCtx.clearRect(0, 0, nWidth, nHeight);
+    oColorImg.style.display = "none";
+    oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
+  }
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("api.HTMLCanvasElement.toDataURL")}}

+ +

Veja também

+ + -- cgit v1.2.3-54-g00ecf