Método HTML canvas drawImage()
Imagen a usar:
Ejemplo
Dibuja la imagen en el lienzo:
JavaScript:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
Compatibilidad con navegador
Los números en la tabla especifican la primera versión del navegador que soporta totalmente este método.
Method | |||||
---|---|---|---|---|---|
drawImage() | 4.0 | 9.0 | 3.6 | 4.0 | 10.1 |
Definición y uso
El método drawImage() dibuja una imagen, lienzo o video en el lienzo.
El método drawImage() también puede dibujar partes de una imagen y/o aumentar/reducir el tamaño de la imagen.
Sintaxis JavaScript
Coloque la imagen en el lienzo:
Sintaxis de JavaScript: | contexto .drawImage( img, x, y ); |
---|
Coloque la imagen en el lienzo y especifique el ancho y el alto de la imagen:
JavaScript syntax: | context.drawImage(img, x, y, width, height); |
---|
Recorta la imagen y coloca la parte recortada en el lienzo:
JavaScript syntax: | context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height); |
---|
Valores paramétricos
Parameter | Description | Play it |
---|---|---|
img | Specifies the image, canvas, or video element to use | |
sx | Optional. The x coordinate where to start clipping | |
sy | Optional. The y coordinate where to start clipping | |
swidth | Optional. The width of the clipped image | |
sheight | Optional. The height of the clipped image | |
x | The x coordinate where to place the image on the canvas | |
y | The y coordinate where to place the image on the canvas | |
width | Optional. The width of the image to use (stretch or reduce the image) | |
height | Optional. The height of the image to use (stretch or reduce the image) |
Más ejemplos
Ejemplo
Coloque la imagen en el lienzo y especifique el ancho y el alto de la imagen:
JavaScript:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10, 150, 180);
Ejemplo
Recorta la imagen y coloca la parte recortada en el lienzo:
JavaScript:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 90, 130, 50, 60, 10, 10, 50, 60);
Ejemplo
Vídeo a utilizar (presione Play para iniciar la demostración):
Lienzo:
JavaScript (el código dibuja el cuadro actual del video cada 20 milisegundos):
var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
ctx = c.getContext('2d');
v.addEventListener('play', function() {var i = window.setInterval(function()
{ctx.drawImage(v, 5, 5, 260, 125)}, 20);}, false);
v.addEventListener('pause', function() {window.clearInterval(i);}, false);
v.addEventListener('ended', function() {clearInterval(i);}, false);
❮ Objeto de lienzo