2012-05-29 14 views
13

usuarios Hola RaphaelJS =),Raphael.js - imagen con su tamaño original de ancho y alto?

que tienen tal vez una pregunta tonta-ish, pero me parece que no puede encontrar la respuesta, la cosa es que yo estoy tratando de cargar/crear una imagen con Rafael, que es bien, como esto:

var image_1 = paper.image('/img/img1.jpg', 0, 0, 100, 100); 

pero como se puede ver, siempre parece como si tuviera que dar a los y las propiedades "ancho", "altura", ya comprobada la documentación, pero siempre es corto y no que es detallada , y traté de dar parámetros nulos o parámetros vacíos, pero no funciona ...

Así que me pregunto si realmente hay una forma directa en raphael para hacer esto, o ... ¿Tengo que obtener siempre esos valores antes de ???

quiero decir, algo como esto ?:

var imgURL = "../img/img1.jpg" 

var myImg = new Image(); 
myImg.src = imgURL; 

var width = myImg.width; 
var height = myImg.height; 

    //create the image with the obtained width and height: 
    var image_1 = paper.image('/img/img1.jpg', 0, 0, width, height); 

Y así, de esa manera me carga con el tamaño original de la imagen y que soluciona un poco mi problema, pero .... no hay manera dentro de Raphael para hacer esto?

+0

¿Qué le impide implementarlo como sugirió? ser más claro, ¿qué estás tratando de lograr? –

+0

@EliranMalka, umm, nada me detiene, lo implementé de la manera que dije, pero, mi pregunta era ... si en lugar de hacer todo ese código ... Raphael tiene un argumento/parámetro/propiedad para crear una imagen con las dimensiones originales? ,¿Ha quedado claro? o ¿qué me estoy perdiendo? = P – Edward

+0

¿Has encontrado una solución?también lo estoy buscando – oyatek

Respuesta

14

Por ahora ... Creo que voy a tener que responder a mi propia pregunta con mi propia respuesta, hacer que no parece haber ninguna otra manera que he encontrado o que alguien me ha dicho = P

var imgURL = "../img/img1.jpg" 

var myImg = new Image(); 
myImg.src = imgURL; 

var width = myImg.width; 
var height = myImg.height; 

    //create the image with the obtained width and height: 
    var image_1 = paper.image('/img/img1.jpg', 0, 0, width, height); 
+0

Gracias por la respuesta. También estaba mirando en la misma línea y me encontré usando a tu manera también y ahora has confirmado que no es malo =) – Sultanen

3

Had mismo problema, gracias por la punta - aquí hay un plugin para reemplazar la función de imagen existente con uno que respeta dimensiones: http://jsfiddle.net/drzaus/dhkh7/

ser más seguro, probablemente no debería sobrescribir la función de imagen original en caso de que alguna vez cambia, pero entiendes la idea.

;(function(Raphael){ 
/// Plugin - replaces original RaphaelJS .image constructor 
/// with one that respects original dimensions. 
/// Optional overrides for each dimension. 
/// @drzaus @zaus 
/// based on http://stackoverflow.com/questions/10802702/raphael-js-image-with-its-original-width-and-height-size 

var originalRaphaelImageFn = Raphael.fn.image; 
Raphael.fn.image = function(url, x, y, w, h) { 
    // fix the image dimensions to match original scale unless otherwise provided 
    if(!w || !h) { 
     var img = new Image(); 
     img.src = url; 
     if(!w) w = img.width; 
     if(!h) h = img.height; 
    } 
    return originalRaphaelImageFn.call(this, url, x, y, w, h); 
}; 
})(Raphael); 

y uso:

window.onload = function() { 
    var paper = new Raphael('canvas', '100%', '100%'); 

    // specify dimensions as before 
    paper.image('http://www.stockfreeimages.com/Swiss-panorama-thumb6499792.jpg', 10, 10, 100, 50).attr('stroke', '#000'); 

    // original ratio 
    paper.image('http://www.stockfreeimages.com/Swiss-panorama-thumb6499792.jpg', 10, 100).attr('stroke', '#f00'); 

    // specify width, height taken from original 
    paper.image('http://www.stockfreeimages.com/Swiss-panorama-thumb6499792.jpg', 10, 200, 100).attr('stroke', '#0f0'); 

    // specify height, width taken from original 
    paper.image('http://www.stockfreeimages.com/Swiss-panorama-thumb6499792.jpg', 10, 300, false, 100).attr('stroke', '#00f'); 
}; 
7

edificio fuera de respuesta increíble de @ drzaus, tuve algunos problemas en el que si la imagen que estaba cargando en Rafael no estaba ya en la memoria caché, la altura y la anchura haría establecer en 0. para solucionar este:

(function(Raphael){ 
/// Plugin - replaces original RaphaelJS .image constructor 
/// with one that respects original dimensions. 
/// Optional overrides for each dimension. 
/// @drzaus @zaus 
/// based on http://stackoverflow.com/questions/10802702/raphael-js-image-with-its-original-width-and-height-size 
/// modified 13/08/2013 by @Huniku to support asynchronous loads 

var originalRaphaelImageFn = Raphael.fn.image; 

Raphael.fn.imageAsync = function(url, x, y, w, h) { 
    var dfd = new jQuery.Deferred(); 
    var done = false; 
    var paper = this; 
    // fix the image dimensions to match original scale unless otherwise provided 
    if(!w || !h) { 
     //Create the new image and set the onload event to call 
     //the original paper.image function with the desired dimensions 
     var img = new Image(); 
     img.onload = function() { 
      if(done) 
       return; 
      if(!w) w = img.width; 
      if(!h) h = img.height; 
      dfd.resolve(originalRaphaelImageFn.call(paper, url, x, y, w, h)); 
     }; 
     //Begin loading of the image 
     img.src = url; 

     //If the images is already loaded (i.e. it was in the local cache) 
     //img.onload will not fire, so call paper.image here. 
     //Set done to ensure img.onload does not fire. 
     if(img.width != 0) { 
      if(!w) w = img.width; 
      if(!h) h = img.height; 
      done = true; 
      dfd.resolve(originalRaphaelImageFn.call(paper, url, x, y, w, h)); 
     } 
    } 
    else 
     dfd.resolve(originalRaphaelImageFn.call(paper, url, x, y, w, h)); 
    return dfd.promise(); 
}; 
})(Raphael); 

esto permite que la imagen se cargue antes antes de consultar por anchura/altura, y también es compatible con el caso en que la imagen ya está en la memoria caché y la ONL El evento de oad no se dispara. Para utilizarlo, sólo tiene:

var dfd = paper.imageAsync("images/hello.png",0,0,false,false); 
dfd.done(function(result) { //result is a Raphael element 
    console.log('done'); 
    //do something with result 
}); 
+1

nice - realmente necesito usar Promises más ... – drzaus

0

comentario de Edward trabajado para mí, pero tuve que colocarlo en una función de intervalo y esperar hasta que la anchura y la altura se definen antes de añadir la imagen (de lo contrario me dieron una imagen de 0x0). Aquí está el código que utilicé:

var imgURL = "/img/img1.jpg" 
var myImg = new Image(); 
myImg.src = imgURL; 

function loadImagAfterWidthAndHeightAreDefined(){ 
    width = myImg.width; 
    height = myImg.height; 

    if(myImg.width > 0 && myImg.height > 0){ 
    image_1 = paper.image(imgURL, 0, 0, width, height); 
    } 
    else{ 
    setTimeout(function(){ 
     loadImagAfterWidthAndHeightAreDefined(); 
    },250); 
    } 
} 
loadImagAfterWidthAndHeightAreDefined() 
Cuestiones relacionadas