From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../api/canvasrenderingcontext2d/arc/index.html | 226 +++++++++ .../canvasrenderingcontext2d/beginpath/index.html | 180 +++++++ .../canvasrenderingcontext2d/clearrect/index.html | 203 ++++++++ .../canvasrenderingcontext2d/drawimage/index.html | 232 +++++++++ .../canvasrenderingcontext2d/fillrect/index.html | 169 +++++++ .../getimagedata/index.html | 103 ++++ .../es/web/api/canvasrenderingcontext2d/index.html | 519 +++++++++++++++++++++ .../canvasrenderingcontext2d/linecap/index.html | 131 ++++++ .../api/canvasrenderingcontext2d/rotate/index.html | 137 ++++++ .../api/canvasrenderingcontext2d/save/index.html | 91 ++++ 10 files changed, 1991 insertions(+) create mode 100644 files/es/web/api/canvasrenderingcontext2d/arc/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/beginpath/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/clearrect/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/drawimage/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/fillrect/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/linecap/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/rotate/index.html create mode 100644 files/es/web/api/canvasrenderingcontext2d/save/index.html (limited to 'files/es/web/api/canvasrenderingcontext2d') diff --git a/files/es/web/api/canvasrenderingcontext2d/arc/index.html b/files/es/web/api/canvasrenderingcontext2d/arc/index.html new file mode 100644 index 0000000000..db4803a7ab --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/arc/index.html @@ -0,0 +1,226 @@ +--- +title: CanvasRenderingContext2D.arc() +slug: Web/API/CanvasRenderingContext2D/arc +translation_of: Web/API/CanvasRenderingContext2D/arc +--- +
{{APIRef}}
+ +

El método CanvasRenderingContext2D .arc() de la API de Canvas 2D añade un arco a la trayectoria centrada en la posición (x, y) con el radio r comenzando en startAngle y terminando en endAngle que va en la dirección dada en sentido antihorario (predeterminado en sentido  horario) .

+ +

Sintaxis

+ +
Void ctx .arc (x, y, radio, startAngle, endAngle, antihorario);
+ +

Parámetros

+ +
+
x
+
La coordenada x del centro del arco.
+
y
+
La coordenada y del centro del arco.
+
radius
+
El radio del arco.
+
startAngle
+
El ángulo en el que se inicia el arco, medido en sentido horario desde el eje x positivo y expresado en radianes.
+
endAngle
+
El ángulo en el que termina el arco, medido en sentido horario desde el eje x positivo y expresado en radianes.
+
anticlockwise Opcional
+
Un Boolean opcional que, si es true , hace que el arco se dibuje en sentido contrario a las agujas del reloj entre los dos ángulos. De forma predeterminada, se dibuja en el sentido de las agujas del reloj.
+
+ +

Ejemplos

+ +

Utilizando el método del arc

+ +

Esto es sólo un simple fragmento de código dibujando un círculo.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.arc(75, 75, 50, 0, 2 * Math.PI);
+ctx.stroke();
+
+ +

Edite el código de abajo y vea su actualización de cambios en vivo en el lienzo:

+ +
+
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.beginPath();
+ctx.arc(50, 50, 50, 0, 2 * Math.PI, false);
+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();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Diferentes formas demostradas

+ +

En este ejemplo se dibujan diferentes formas para mostrar lo que es posible al usar arc() .

+ +
+
HTML
+ +
<canvas id="canvas" width="150" height="200"></canvas>
+
+ +
JavaScript
+
+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Draw shapes
+for (var i = 0; i < 4; i++) {
+  for(var j = 0; j < 3; j++) {
+    ctx.beginPath();
+    var x              = 25 + j * 50;               // x coordinate
+    var y              = 25 + i * 50;               // y coordinate
+    var radius         = 20;                    // Arc radius
+    var startAngle     = 0;                     // Starting point on circle
+    var endAngle       = Math.PI + (Math.PI * j) /2; // End point on circle
+    var anticlockwise  = i % 2 == 1;                // Draw anticlockwise
+
+    ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+    if (i > 1) {
+      ctx.fill();
+    } else {
+      ctx.stroke();
+    }
+  }
+}
+ +

{{ EmbedLiveSample('Different_shapes_demonstrated', 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png") }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + +
EspecificaciónEstadoComentarioWHATWG HTML Estándar de vida
+ La definición de 'CanvasRenderingContext2D.arc' en esa especificación.
Estándar de vidaStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-arc", "CanvasRenderingContext2D.arc")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad del navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Notas específicas de Gecko

+ +

Comenzando con Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1):

+ + + +

Ver también

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/beginpath/index.html b/files/es/web/api/canvasrenderingcontext2d/beginpath/index.html new file mode 100644 index 0000000000..1c91e264f4 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/beginpath/index.html @@ -0,0 +1,180 @@ +--- +title: CanvasRenderingContext2D.beginPath() +slug: Web/API/CanvasRenderingContext2D/beginPath +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/beginPath +--- +
{{APIRef}}
+ +

El método CanvasRenderingContext2D.beginPath() del API Canvas 2D comienza una nueva ruta vaciando la lista de sub-rutas. Invoca este método cuando quieras crear una nueva ruta. 

+ +

Sintaxis

+ +
void ctx.beginPath();
+
+ +

Ejemplos

+ +

Usando el método beginPath

+ +

Este es solo un trozo de código el cual usa el método beginPath.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// First path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.stroke();
+
+// Second path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20,20);
+ctx.lineTo(120,120);
+ctx.stroke();
+
+ +

Edita el código aquí debajo y mira tus cambios actualizarse en vivo en el canvas:

+ +
+
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" style="height:200px">
+// First path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.stroke();
+
+// Second path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20,20);
+ctx.lineTo(120, 120);
+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();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 460) }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstatusComentario
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-beginpath", "CanvasRenderingContext2D.beginPath")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad de los navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver también

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/clearrect/index.html b/files/es/web/api/canvasrenderingcontext2d/clearrect/index.html new file mode 100644 index 0000000000..64aa1a3908 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/clearrect/index.html @@ -0,0 +1,203 @@ +--- +title: CanvasRenderingContext2D.clearRect() +slug: Web/API/CanvasRenderingContext2D/clearRect +translation_of: Web/API/CanvasRenderingContext2D/clearRect +--- +
{{APIRef}}
+ +
El método CanvasRenderingContext2D.clearRect() del API Canvas 2D convierte todos los pixeles en el rectangulo definido por el punto de inicio (x, y) y tamaño (width, height) a negro transparente, borrando cualquier contenido dibujado anteriormente.
+ +
 
+ +

Syntaxis

+ +
+

HTML Content

+ +
void ctx.clearRect(x, y, width, height);
+ +

Parametros

+ +
+
x
+
El eje  de la coordenada para el punto de inicio del rectangulo.
+
y
+
El eje  de la coordenada para el punto de inicio del rectangulo.
+
width
+
El ancho del rectangulo.
+
heigth
+
el alto del rectangulo.
+
+ +

Notas de uso

+ +

Un problema común con clearRect es que puede parecer que no funciona cuando no se usan las trayectorias de dibujo (paths) de forma adecuada. No olvide llamar {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} antes de comenzar a dibujar el nuevo cuadro después de llamar clearRect.

+ +

Ejemplos

+ +
+
+

Usando el método clearRect

+
+
+ +

  Este es un simple fragmento (snippet) de código que usa el método clearRect.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d'); c
+
+tx.beginPath(); ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.lineTo(120, 120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();
+
+ctx.clearRect(10, 10, 100, 100);
+
+// clear the whole canvas
+// ctx.clearRect(0, 0, canvas.width, canvas.height);
+ +

  

+ +

Edite el código de abajo y vea sus cambios actualizados en vivo en el canvas:

+ +

{{ EmbedLiveSample('Playable_code', 700, 400) }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clearrect", "CanvasRenderingContext2D.clearRect")}}{{Spec2('HTML WHATWG')}} 
+ +
+
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" style="height:140px;">
+ctx.beginPath();
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.lineTo(120,120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();
+
+ctx.clearRect(10, 10, 100, 100);</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();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+
+ + + + +
+ +

Compatibilidad con exploradores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracteristicaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte Basico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Vea También

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/drawimage/index.html b/files/es/web/api/canvasrenderingcontext2d/drawimage/index.html new file mode 100644 index 0000000000..2d5330ec53 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/drawimage/index.html @@ -0,0 +1,232 @@ +--- +title: CanvasRenderingContext2D.drawImage() +slug: Web/API/CanvasRenderingContext2D/drawImage +tags: + - API + - Canvas + - CanvasRenderingContect2D + - Métodos + - Referencia +translation_of: Web/API/CanvasRenderingContext2D/drawImage +--- +
{{APIRef}}
+ +

El método CanvasRenderingContext2D.drawImage() de la API Canvas 2D proporciona diferentes formas para dibujar una imagen dentro de canvas.

+ +

Sintaxis

+ +
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);
+
+ +

drawImage

+ +

Parámetros

+ +
+
image
+
Un elemento a dibujar dentro del context. La especificación permite cualquier fuente de imagen en canvas ({{domxref("CanvasImageSource")}}), tal como una {{domxref("HTMLImageElement")}}, un {{domxref("HTMLVideoElement")}}, un {{domxref("HTMLCanvasElement")}} o un{{domxref("ImageBitmap")}}.
+
dx
+
La coordenada X del canvas destino en la cual se coloca la esquina superior izquierda de la imagen origen.
+
dy
+
La coordenada Y del canvas destino en la cual se coloca la esquina superior izquierda de la imagen origen.
+
dWidth
+
El ancho para dibujar la imagen en el canvas destino.
+
dHeight
+
El alto para dibujar la imagen en el canvas destino. Esto permite escalar la imagen dibujada. Si no se especifica, el alto de  la imagen no se escala al dibujar.
+
sx
+
La coordenada X de la esquina superior izquierda del sub-rectangulo de la imagen origen a dibujar en el contexto de destino.
+
sy
+
La coordenada Y de la esquina superior izquierda del sub-rectangulo de la imagen origen a dibujar en el contexto de destino.
+
sWidth
+
El ancho del sub-rectangulo de la imagen origen a dibujar en el contexto de destino. Si no se especifica, se utiliza todo el rectangulo entero desde las coordenadas especificadas por sxsy hasta la esquina inferior derecha de la imagen.
+
sHeight
+
La altura del sub-rectangulo de la imagen origen a dibujar en el contexto de destino.
+
+ +

Excepciones lanzadas

+ +
+
INDEX_SIZE_ERR
+
Si el canvas o la fuente de anchura o altura del rectangulo es igual a cero.
+
INVALID_STATE_ERR
+
La imagen no tiene datos de imagen.
+
TYPE_MISMATCH_ERR
+
El elemento de origen especificado no es compatible.
+
+ +

Ejemplos

+ +

Usando el método drawImage

+ +

Este es sólo un simple fragmento de código que utiliza el método drawImage.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+<div style="display:none;">
+  <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg"
+       width="300" height="227">
+</div>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var image = document.getElementById('source');
+
+ctx.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);
+
+ +

Edita el código debajo y observa los cambios actualizarse en vivo en el canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div style="display:none;">
+  <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
+</div>
+<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.drawImage(image, 33, 71, 104, 124, 21, 20, 87, 104);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var image = document.getElementById('source');
+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();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-drawimage", "CanvasRenderingContext2D.drawImage")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ImageBitmap como fuente de imagen{{CompatUnknown}}{{CompatGeckoDesktop(42)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ImageBitmap como fuente de imagen{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(42)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

+ +

Notas de compatibilidad

+ + + +

Mira también

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/fillrect/index.html b/files/es/web/api/canvasrenderingcontext2d/fillrect/index.html new file mode 100644 index 0000000000..bc1a6ddf65 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/fillrect/index.html @@ -0,0 +1,169 @@ +--- +title: CanvasRenderingContext2D.fillRect() +slug: Web/API/CanvasRenderingContext2D/fillRect +translation_of: Web/API/CanvasRenderingContext2D/fillRect +--- +
{{APIRef}}
+ +

El método CanvasRenderingContext2D.fillRect()  de la API Canvas 2D dibuja un rectángulo relleno en la posición ( x, y ). El tamaño del rectángulo se determina por width (anchura) y height (altura). El estilo de relleno se determina por el atributo fillStyle.

+ +

Sintaxis

+ +
void ctx.fillRect(x, y, width, height);
+
+ +

Parámetros

+ +
+
x
+
La componente x de la coordenada para el punto de comienzo del rectángulo.
+
y
+
La componente y de la coordenada para el punto de comienzo del rectángulo.
+
width
+
La anchura del rectángulo.
+
height
+
La altura del rectángulo.
+
+ +

Ejemplos

+ +

Usando el método fillRect

+ +

El siguiente fragmento de código usa el método fillRect.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);
+
+// Rellenar el canvas completo
+// ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ +

Edita el código  que se encuentra a continuación y observa en vivo los cambios actualizados en el canvas:

+ +
+
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.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);</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();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad del navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Soporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Documentos relacionados

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html b/files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html new file mode 100644 index 0000000000..4f0c72afd0 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/getimagedata/index.html @@ -0,0 +1,103 @@ +--- +title: CanvasRenderingContext2D.getImageData() +slug: Web/API/CanvasRenderingContext2D/getImageData +tags: + - CanvasRenderingContext2D + - Context 2D + - Español + - Method + - Reference + - getImageData +translation_of: Web/API/CanvasRenderingContext2D/getImageData +--- +
{{APIRef}}
+ +

 

+ +

El método CanvasRenderingContext2D.getImageData() de la API de Canvas 2D devuelve un objeto ImageData que representa los datos de píxeles subyacentes para el área del lienzo denotada por el rectángulo que comienza en (sx, sy) y tiene un ancho de sw y una altura de sh. Este método no se ve afectado por la matriz de transformación de la lona.

+ +

Los píxeles fuera del área del lienzo están presentes como valores negros transparentes en los datos de imagen devueltos.

+ +

 

+ +

Sintaxis

+ +
ImageData ctx.getImageData(sx, sy, sw, sh);
+
+ +

Parámetros

+ +
+
sx
+
La coordenada 'x' de la esquina superior izquierda del rectángulo del que se extraerán los datos de imagen.
+
sy
+
La coordenada 'y' de la esquina superior izquierda del rectángulo del que se extraerá el ImageData.
+
sw
+
El ancho del rectángulo del que se extraerán los datos de la imagen.
+
sh
+
La altura del rectángulo del que se extraerán los datos de la imagen.
+
+ +

Valor de retorno

+ +

An ImageData object containing the image data for the given rectangle of the canvas.

+ +

Errores cometidos

+ +
+
IndexSizeError
+
Lanzado si cualquiera de los argumentos de anchura o altura es cero.
+
+ +

Ejemplos

+ +

Usando el método getImageData

+ +

Esto es sólo un simple fragmento de código que utiliza el método getImageData. Para obtener más información, consulte Manipulación de píxeles con Canvas y el objeto ImageData.

+ +

HTML

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

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+console.log(ctx.getImageData(50, 50, 100, 100));
+// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }
+
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-getimagedata", "CanvasRenderingContext2D.getImageData")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad con navegadores

+ + + +

{{Compat("api.CanvasRenderingContext2D.getImageData")}}

+ +

Véase también

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/index.html b/files/es/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..77df4af190 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,519 @@ +--- +title: CanvasRenderingContext2D +slug: Web/API/CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D +--- +
{{APIRef}}
+ +

La interfaz CanvasRenderingContext2D proporciona el contexto de renderizado 2D para la superficie de dibujo de un elemento {{ HTMLElement("canvas") }}.

+ +

Para obtener un objeto de esta interfaz, llama a {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} en un <canvas>, proporcionando "2d" como argumento:

+ +
var canvas = document.getElementById('mycanvas');
+var ctx = canvas.getContext('2d');
+
+ +

Una vez que tengas el contexto de renderizado 2D para un canvas, podrás dibujar en ella. Por ejemplo:

+ +
ctx.fillStyle = "rgb(200,0,0)";
+ctx.fillRect(10, 10, 55, 50);
+
+ +

Mira las propiedades y métodos en la barra lateral. El tutorial de canvas tiene más información, ejemplos y recursos también.

+ +

Dibujando rectángulos

+ +

Hay 3 métodos que inmediatamente dibujan rectángulos en el bitmap.

+ +
+
{{domxref("CanvasRenderingContext2D.clearRect()")}}
+
Establece todos los píxeles del rectangulo definido por los puntos (x, y) y tamaños (ancho, alto) a negro transparente, borrando cualquier contenido previo.
+
{{domxref("CanvasRenderingContext2D.fillRect()")}}
+
Dibuja un rectángulo relleno en la posición (x, y) cuyo tamaño está determinado por la anchura y la altura.
+
{{domxref("CanvasRenderingContext2D.strokeRect()")}}
+
Dibuja un rectángulo que tiene como posición inicial (x, y) con un ancho w y altura h sobre el canvas, utilizando el estilo de trazo actual.
+
+ +

Dibujando texto

+ +

Los siguientes métodos  se proporcionan para dibujar texto. Mira también el objeto {{domxref("TextMetrics")}} para propiedades de texto.

+ +
+
{{domxref("CanvasRenderingContext2D.fillText()")}}
+
Dibuja (llena) un texto dado en una posición (x, y) dada.
+
{{domxref("CanvasRenderingContext2D.strokeText()")}}
+
Dibuja (trazas) un texto dado en una posición (x, y) dada.
+
{{domxref("CanvasRenderingContext2D.measureText()")}}
+
Devuelve el objeto {{domxref("TextMetrics")}}.
+
+ +

Los estilos de línea

+ +

Los siguientes métodos y propiedades controlan como las líneas son dibujadas.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth")}}
+
Ancho de líneas. Por defecto 1.0
+
{{domxref("CanvasRenderingContext2D.lineCap")}}
+
Tipo de terminaciones en el final de las líneas. Posibles valores: butt (defecto), round, square.
+
{{domxref("CanvasRenderingContext2D.lineJoin")}}
+
Define el tipo de esquinas donde dos líneas se encuentran. Pislbes valores: round, bevel, miter (defecto).
+
{{domxref("CanvasRenderingContext2D.miterLimit")}}
+
Relación límite angular. Defecto 10.
+
{{domxref("CanvasRenderingContext2D.getLineDash()")}}
+
Devuelve la matriz patrón de trazos actual que contiene un número de par de números no negativos.
+
{{domxref("CanvasRenderingContext2D.setLineDash()")}}
+
Establece el patrón de trazos linea actual.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+
Especifica donde inicia una gama de instrumentos en una línea.
+
+ +

Estilos de texto

+ +

Las siguientes propiedades control como el texto es presentado.

+ +
+
{{domxref("CanvasRenderingContext2D.font")}}
+
Ajuste de fuente. Valor por defecto 10px sans-serif.
+
{{domxref("CanvasRenderingContext2D.textAlign")}}
+
Text alignment setting. Possible values: start (default), end, left, right or center.
+
{{domxref("CanvasRenderingContext2D.textBaseline")}}
+
Baseline alignment setting. Possible values: top, hanging, middle, alphabetic (default), ideographic, bottom.
+
{{domxref("CanvasRenderingContext2D.direction")}}
+
Directionality. Possible values: ltr, rtl, inherit (default).
+
+ +

Estilo del relleno y de los bordes

+ +

Fill styling es utilizado para estilizar los colores del relleno y los bordes de las  formas.

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle")}}
+
Utilizado para dar color al relleno de las formas. Color por defecto #000 (negro).
+
{{domxref("CanvasRenderingContext2D.strokeStyle")}}
+
Utilizado para dar color al borde de las formas. Color por defecto #000 (negro)..
+
+ +

Degradados y patrones

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+
Creates a linear gradient along the line given by the coordinates represented by the parameters.
+
{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+
Creates a radial gradient along the line given by the coordinates represented by the parameters.
+
{{domxref("CanvasRenderingContext2D.createPattern()")}}
+
Creates a pattern using the specified image (a {{domxref("CanvasImageSource")}}). It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}.
+
+ +

Sombras

+ +
+
{{domxref("CanvasRenderingContext2D.shadowBlur")}}
+
Especifica el efecto de desenfoque. Predeterminado 0
+
{{domxref("CanvasRenderingContext2D.shadowColor")}}
+
Color de la sombra. Predeterminado totalmente transparente negro.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+
Distancia horizontal del desplazamiento de la sombra. Predeterminado 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+
Distancia vertical del desplazamiento de la sombra. Predeterminado 0.
+
+ +

Paths

+ +

The following methods can be used to manipulate paths of objects.

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath()")}}
+
Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
+
{{domxref("CanvasRenderingContext2D.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.
+
{{domxref("CanvasRenderingContext2D.moveTo()")}}
+
Moves the starting point of a new sub-path to the (x, y) coordinates.
+
{{domxref("CanvasRenderingContext2D.lineTo()")}}
+
Connects the last point in the subpath to the x, y coordinates with a straight line.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+
Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using moveTo() before creating the Bézier curve.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+
Adds a quadratic Bézier curve to the current path.
+
{{domxref("CanvasRenderingContext2D.arc()")}}
+
Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
+
{{domxref("CanvasRenderingContext2D.arcTo()")}}
+
Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.
+
{{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}
+
Adds an ellipse to the path which is centered at (x, y) position with the radii radiusX and radiusY starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
+
{{domxref("CanvasRenderingContext2D.rect()")}}
+
Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.
+
+ +

Drawing paths

+ +
+
{{domxref("CanvasRenderingContext2D.fill()")}}
+
Fills the subpaths with the current fill style.
+
{{domxref("CanvasRenderingContext2D.stroke()")}}
+
Strokes the subpaths with the current stroke style.
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
+
If a given element is focused, this method draws a focus ring around the current path.
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
+
Scrolls the current path or a given path into the view.
+
{{domxref("CanvasRenderingContext2D.clip()")}}
+
Creates a clipping path from the current sub-paths. Everything drawn after clip() is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial.
+
{{domxref("CanvasRenderingContext2D.isPointInPath()")}}
+
Reports whether or not the specified point is contained in the current path.
+
{{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
+
Reports whether or not the specified point is inside the area contained by the stroking of a path.
+
+ +

Transformations

+ +

Objects in the CanvasRenderingContext2D rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("SVGMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.

+ +
+
{{domxref("CanvasRenderingContext2D.currentTransform")}}
+
Current transformation matrix ({{domxref("SVGMatrix")}} object).
+
{{domxref("CanvasRenderingContext2D.rotate()")}}
+
Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
+
{{domxref("CanvasRenderingContext2D.scale()")}}
+
Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
+
{{domxref("CanvasRenderingContext2D.translate()")}}
+
Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
+
{{domxref("CanvasRenderingContext2D.transform()")}}
+
Multiplies the current transformation matrix with the matrix described by its arguments.
+
{{domxref("CanvasRenderingContext2D.setTransform()")}}
+
Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments.
+
{{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
+
Resets the current transform by the identity matrix.
+
+ +

Compositing

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha")}}
+
Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
+
{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
+
With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.
+
+ +

Drawing images

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage()")}}
+
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
+
+ +

Pixel manipulation

+ +

See also the {{domxref("ImageData")}} object.

+ +
+
{{domxref("CanvasRenderingContext2D.createImageData()")}}
+
Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.
+
{{domxref("CanvasRenderingContext2D.getImageData()")}}
+
Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height.
+
{{domxref("CanvasRenderingContext2D.putImageData()")}}
+
Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
+
+ +

Image smoothing

+ +
+
{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+
Image smoothing mode; if disabled, images will not be smoothed if scaled.
+
+ +

The canvas state

+ +

The CanvasRenderingContext2D rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

+ +
+
{{domxref("CanvasRenderingContext2D.save()")}}
+
Saves the current drawing style state using a stack so you can revert any change you make to it using restore().
+
{{domxref("CanvasRenderingContext2D.restore()")}}
+
Restores the drawing style state to the last element on the 'state stack' saved by save().
+
{{domxref("CanvasRenderingContext2D.canvas")}}
+
A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
+
+ +

Hit regions

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
Adds a hit region to the canvas.
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
Removes the hit region with the specified id from the canvas.
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
Removes all hit regions from the canvas.
+
+ +

Non-standard APIs

+ + + +

Most of these APIs are deprecated and will be removed in the future.

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.clearShadow()
+
Removes all shadow settings like {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+
{{non-standard_inline}} CanvasRenderingContext2D.drawImageFromRect()
+
This is redundant with an equivalent overload of drawImage.
+
{{non-standard_inline}} CanvasRenderingContext2D.setAlpha()
+
Use {{domxref("CanvasRenderingContext2D.globalAlpha")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setCompositeOperation()
+
Use {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineWidth()
+
Use {{domxref("CanvasRenderingContext2D.lineWidth")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineJoin()
+
Use {{domxref("CanvasRenderingContext2D.lineJoin")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineCap()
+
Use {{domxref("CanvasRenderingContext2D.lineCap")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setMiterLimit()
+
Use {{domxref("CanvasRenderingContext2D.miterLimit")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setStrokeColor()
+
Use {{domxref("CanvasRenderingContext2D.strokeStyle")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setFillColor()
+
Use {{domxref("CanvasRenderingContext2D.fillStyle")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setShadow()
+
Use {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDash
+
Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDashOffset
+
Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitImageSmoothingEnabled
+
Use {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} instead.
+
+ + + +
+
{{non-standard_inline}} CanvasRenderingContext2D.getContextAttributes()
+
Inspired by the same WebGLRenderingContext method it returns an Canvas2DContextAttributes object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (true by default) to indicate that transparency is used in the canvas.
+
{{non-standard_inline}} CanvasRenderingContext2D.isContextLost()
+
Inspired by the same WebGLRenderingContext method it returns true if the Canvas context has been lost, or false if not.
+
+ +

WebKit only

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitBackingStorePixelRatio
+
The backing store size in relation to the canvas element. See High DPI Canvas.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitGetImageDataHD
+
Intended for HD backing stores, but removed from canvas specifications.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitPutImageDataHD
+
Intended for HD backing stores, but removed from canvas specifications.
+
+ +
+
+ +

Gecko only

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
+
CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.
+
+ +

Prefixed APIs

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransform
+
Sets or gets the current transformation matrix, see {{domxref("CanvasRenderingContext2D.currentTransform")}}.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransformInverse
+
Sets or gets the current inversed transformation matrix.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozFillRule
+
The fill rule to use. This must be one of evenodd or nonzero (default).
+
{{non-standard_inline}} CanvasRenderingContext2D.mozImageSmoothingEnabled
+
See {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDash
+
An array which specifies the lengths of alternating dashes and gaps {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDashOffset
+
Specifies where to start a dash array on a line. {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozTextStyle
+
Introduced in in Gecko 1.9, deprecated in favor of the {{domxref("CanvasRenderingContext2D.font")}} property.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozDrawText()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.strokeText()")}} or {{domxref("CanvasRenderingContext2D.fillText()")}} instead.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozMeasureText()
+
This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.measureText()")}} instead.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozPathText()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozTextAlongPath()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
+ +

Internal APIs (chrome-context only)

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}
+
Renders a region of a XUL element into the canvas.
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}
+
Renders a region of a window into the canvas. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.
+
{{non-standard_inline}} CanvasRenderingContext2D.demote()
+
This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.
+
+ +

Internet Explorer

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.msFillRule
+
The fill rule to use. This must be one of evenodd or nonzero (default).
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#2dcontext:canvasrenderingcontext2d", "CanvasRenderingContext2D")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatOpera("9")}}{{CompatSafari("2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Compatibility notes

+ + + +

See also

+ + + +
+ + + + + +
diff --git a/files/es/web/api/canvasrenderingcontext2d/linecap/index.html b/files/es/web/api/canvasrenderingcontext2d/linecap/index.html new file mode 100644 index 0000000000..e61f3c1465 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/linecap/index.html @@ -0,0 +1,131 @@ +--- +title: CanvasRenderingContext2D.lineCap +slug: Web/API/CanvasRenderingContext2D/lineCap +translation_of: Web/API/CanvasRenderingContext2D/lineCap +--- +
{{APIRef}}
+ +

La propiedad CanvasRenderingContext2D.lineCap del API Canvas 2D determina la forma usada para dibujar los puntos finales de las líneas.

+ +
+

Nota: La líneas se puede dibujar con los métodos {{domxref("CanvasRenderingContext2D.stroke()", "stroke()")}}, {{domxref("CanvasRenderingContext2D.strokeRect()", "strokeRect()")}}, y {{domxref("CanvasRenderingContext2D.strokeText()", "strokeText()")}}.

+
+ +

Sintaxis

+ +
ctx.lineCap = "butt" || "round" || "square";
+
+ +

Opciones

+ +
+
"butt"
+
Los finales de las líneas son recortados. Valor por defecto.
+
"round"
+
Los finales de las líneas son redondeados.
+
"square"
+
Los finales de líneas son recortados al agregar un cuadrado de ancho y altura igual que el grosor de línea.
+
+ +

Ejemplos

+ +

Cambiando los finales de línea

+ +

En este ejemplo se redondean los puntos finales de una línea recta.

+ +

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

+ +

{{ EmbedLiveSample('Changing_the_shape_of_line_caps', 700, 180) }}

+ +

Comparando los finales de línea

+ +

En este ejemplo se dibujan 3 líneas, cada una con un valor distinto de la propiedad lineCap. Se agregaron dos guías para resaltar las diferencias entre las tres líneas. Cada una de estas líneas empiezan y terminan en estas guías.

+ +

La línea de la izquiera usa la opción por defecto "butt". Esta es dibujada completamente al ras de las líneas de guía. La segunda esta configurada para usar la opción "round. Esta agrega un semicírculo al final que tiene un radio de la mitad del grosor de línea. La línea de la derecha use la opción "square". Esta agrega un cuadrado con ancho y altura de la mitad del grosor de línea.

+ + + +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+const lineCap = ['butt', 'round', 'square'];
+
+// Draw guides
+ctx.strokeStyle = '#09f';
+ctx.beginPath();
+ctx.moveTo(10, 10);
+ctx.lineTo(140, 10);
+ctx.moveTo(10, 140);
+ctx.lineTo(140, 140);
+ctx.stroke();
+
+// Draw lines
+ctx.strokeStyle = 'black';
+for (let i = 0; i < lineCap.length; i++) {
+  ctx.lineWidth = 15;
+  ctx.lineCap = lineCap[i];
+  ctx.beginPath();
+  ctx.moveTo(25 + i * 50, 10);
+  ctx.lineTo(25 + i * 50, 140);
+  ctx.stroke();
+}
+
+ +

{{EmbedLiveSample("Comparison_of_line_caps", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-linecap", "CanvasRenderingContext2D.lineCap")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad de navegador.

+ + + +

{{Compat("api.CanvasRenderingContext2D.lineCap")}}

+ + + + + +

Ver también

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/rotate/index.html b/files/es/web/api/canvasrenderingcontext2d/rotate/index.html new file mode 100644 index 0000000000..009b280c4c --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/rotate/index.html @@ -0,0 +1,137 @@ +--- +title: CanvasRenderingContext2D.rotate() +slug: Web/API/CanvasRenderingContext2D/rotate +tags: + - metodo +translation_of: Web/API/CanvasRenderingContext2D/rotate +--- +
{{APIRef}}
+ +

El método CanvasRenderingContext2D.rotate() de la API Canvas 2D añade una rotación a la matriz de transformación.

+ +

Sintaxis

+ +
void ctx.rotate(angulo);
+
+ +

+ +

Parámetros

+ +
+
angulo
+
El ángulo de rotación en radianes, en sentido horario. Se puede usar grado* Math.PI / 180 si se quiere calcular a partir de un valor de grado sexagesimal.
+
+ +

El centro de rotación es siempre el orígen del canvas. Para cambiar el centro de rotación hay que mover el canvas mediante el método {{domxref("CanvasRenderingContext2D.translate", "translate()")}}.

+ +

Ejemplos

+ +

Rotando una figura

+ +

En este ejemplo se rota un rectangulo 45º. Nótese que el centro de rotación es la esquina superior izquierda del canvas y no un punto cualquiera relativo a alguna figura.

+ +

HTML

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

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+// origen del punto de transformación
+ctx.arc(0, 0, 5, 0, 2 * Math.PI);
+ctx.fillStyle = 'blue';
+ctx.fill();
+
+// rectángulo sin rotar
+ctx.fillStyle = 'gray';
+ctx.fillRect(100, 0, 80, 20);
+
+// rectángulo rotado 45º
+ctx.rotate(45 * Math.PI / 180);
+ctx.fillStyle = 'red';
+ctx.fillRect(100, 0, 80, 20);
+
+// se reinicia la matriz de transformación a la matriz identidad
+ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ +

Resultado

+ +

El centro de rotación es azul. El rectángulo no rotado es gris, y el rectángulo rotado es rojo.

+ +

{{ EmbedLiveSample('Rotating_a_shape', 700, 180) }}

+ +

Rotando una figura por su centro

+ +

Este ejemplo rota una figura alrededor del punto central de ésta. Para realizarlo se aplican estos pasos a la matriz de transformación:

+ +
    +
  1. Primero, {{domxref("CanvasRenderingContext2D.translate()", "translate()")}} mueve el orígen de la matriz hacia el centro de la figura.
  2. +
  3. rotate() rota la matriz la cantidad deseada.
  4. +
  5. Finalmente, translate() mueve el origen de la matriz de nuevo a su punto inicial. Esto se realiza utilizando los valores del centro de coordenadas de la figura en dirección negativa.
  6. +
+ +

HTML

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

JavaScript

+ +

La figura es un rectángulo con su esquina en (80, 60), un ancho de 140 y un alto de 30. El centro de la coordenada horizontal está en  (80 + 140 / 2) = 150. Su centro en la coordenada vertical será  (60 + 30 / 2) = 75. Por tanto, el punto central está en (150, 75).

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+// rectángulo sin rotar
+ctx.fillStyle = 'gray';
+ctx.fillRect(80, 60, 140, 30);
+
+// Matriz de transformación
+ctx.translate(150, 75);
+ctx.rotate(Math.PI / 2);
+ctx.translate(-150, -75);
+
+// rectángulo rotado
+ctx.fillStyle = 'red';
+ctx.fillRect(80, 60, 140, 30);
+
+ +

Resultado

+ +

El rectángulo no rotado es gris, y el rectángulo rotado es rojo.

+ +

{{ EmbedLiveSample('Rotating_a_shape_around_its_center', 700, 180) }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónStatusComentarios
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-rotate", "CanvasRenderingContext2D.rotate")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidad con exploradores

+ + + +

{{Compat("api.CanvasRenderingContext2D.rotate")}}

+ +

Véase también

+ + diff --git a/files/es/web/api/canvasrenderingcontext2d/save/index.html b/files/es/web/api/canvasrenderingcontext2d/save/index.html new file mode 100644 index 0000000000..6351bb3ad1 --- /dev/null +++ b/files/es/web/api/canvasrenderingcontext2d/save/index.html @@ -0,0 +1,91 @@ +--- +title: CanvasRenderingContext2D.save() +slug: Web/API/CanvasRenderingContext2D/save +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/save +--- +
{{APIRef}}
+ +

El método CanvasRenderingContext2D.save() del API Canvas 2D guarda el estado completo del canvas añadiendo el estado actual a una pila.

+ +

El estado del dibujo

+ +

El estado del dibujo que se almacena en una pila consiste en los siguientes elementos:

+ + + +

Sintaxis

+ +
void ctx.save();
+ +

Ejemplos

+ +

Guardando el estado del dibujo

+ +

Este ejemplo usa el método save() para guardar el estado por defecto y el método restore() para restaurarlo luego, de tal manera que luego se puede dibujar el segundo rectángulo con el estado por defecto.

+ +

HTML

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

JavaScript

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+// Guardar el estado por defecto
+ctx.save();
+
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 100, 100);
+
+// Restaurar el estado por defecto
+ctx.restore();
+
+ctx.fillRect(150, 40, 100, 100);
+
+ +

Resultado

+ +

{{ EmbedLiveSample('Saving_the_drawing_state', 700, 180) }}

+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentarios
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-save", "CanvasRenderingContext2D.save")}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidad con exploradores

+ + + +

{{Compat("api.CanvasRenderingContext2D.save")}}

+ +

Véase también

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