2010-05-04 17 views
26

Estoy trabajando en una nueva función en mi sitio y me pegaron muy mal. Estoy usando JCrop obviamente para recortar una imagen en mi sitio web.Cambiar una imagen mientras usa JCrop

La nueva característica que me pidieron que implemente es permitir al usuario cambiar los colores de la imagen que se está recortando.

que tengo ahora 3 imágenes, color, escala de grises y sepia.

Puedo cambiar la fuente de la etiqueta de imagen usando javascript para que la imagen se cambie sin recargar, pero no puedo hacer esto una vez que se ha habilitado JCrop porque reemplaza la imagen original por una nueva.

Pensé que podría desactivar JCrop, Reemplazar la imagen y luego volver a habilitar, pero no pude hacer tal cosa.

El ejemplo que encontré donde el JCrop se destruye (en zip Example5 Demo) utiliza un objeto:

jcrop_api = $ .Jcrop ('# CropBox');

Pero estoy permitiendo JCrop de una manera diferente, más como Ejemplo 3:

  jQuery('#cropbox').Jcrop({ 
       onChange: showPreview, 
       onSelect: showPreview, 
       aspectRatio: 1 
      }); 

¿Cómo puedo destruir JCrop para que pueda reemplazar te imagen? Hay otra manera de hacer esto?

Podría volver a cargar la página fácilmente cada vez que el usuario cambie el color de la imagen, pero todos sabemos que no es genial.

Respuesta

10

primera pregunta es si las imágenes que están cambiando son del mismo tamaño? Si lo son, lo siguiente debe funcionar:

$(document).ready(function(){ 
    // Just pulled some creative commons images off flickr for testing. 
    var one = "http://farm5.static.flickr.com/4034/4580633003_e62e061b64_d.jpg"; 
    var two = "http://farm5.static.flickr.com/4060/4580650483_7881505c66_d.jpg"; 
    var three = "http://farm5.static.flickr.com/4034/4581278976_0c91bc0f6f_d.jpg"; 

    var api; 

    function showPreview(){ alert('Changed'); } 

    function setCrop() 
    { 
     api = $.Jcrop('#cropBox',{ aspectRatio: 1, onSelect: showPreview }); 
    } 

    // Setup Jcrop for the original image 
    setCrop(); 

    // Change the image and reset Jcrop 
    $('#button').click(function(){ 
     api.destroy(); 
     var i = $('#cropBox').get(0).src = three; 
     setCrop(); 
    });  

}); 

Si las imágenes son de diferentes tamaños cosas son un poco más complicado (intercambio en un retrato para el paisaje?). Tendrá que esperar a que la imagen se cargue para que Jcrop pueda obtener el tamaño correcto de la nueva imagen. La función vailla javascript setTimeout funcionará, pero dado que se ejecuta en alcance global, debe definir algunas cosas globalmente. La desventaja es que tienes que esperar un segundo o dos antes de poder cosechar.

$(document).ready(function(){ 

    var one = "http://farm5.static.flickr.com/4034/4580633003_e62e061b64_d.jpg"; 
    var two = "http://farm5.static.flickr.com/4060/4580650483_7881505c66_d.jpg"; 
    var three = "http://farm5.static.flickr.com/4034/4581278976_0c91bc0f6f_d.jpg"; 

    // api needs to be defined globally so it can be accessed from the setTimeout function 
    $.globalEval("var api;"); 

    // Also need to define your showPreview globally. 
    $.globalEval("function showPreview(){ alert('Changed'); }"); 

    function setCrop() 
    { 
     // Need to pause a second or two to allow the image to load, otherwise the Jcrop plugin 
     // will not update the image size correctly and if you change image size the picture 
     // will be stretched. 
     // Change the 1000 to however many seconds you need to load the new image. 
     setTimeout("api = $.Jcrop('#cropBox',{ aspectRatio: 1, onSelect: showPreview  });",1000); 
    } 

    // Setup Jcrop for the original image 
    setCrop(); 

    // Change the image and reset Jcrop 
    $('#button').click(function(){ 
     api.destroy(); 
     var i = $('#cropBox').get(0).src = two; 
     setCrop(); 
    });  

}); 

Eso debería ser de ayuda. Todo probado para mí en FireFox en jsFiddle. Puedes probarlo here.

3

¡Buena pregunta! sigo pueden salvar a nuestro tiempo,

function initJcrop(id) { 

    jcrop_api = $.Jcrop('#'+id, { 

    onSelect: showCoords, 
    onChange: showCoords, 
    bgColor: 'black', 
    bgOpacity: .4, 
    boxWidth: picture_width, 
    boxHeight: picture_height, 
    setSelect: [ (picture_width * 4/5), 
        (picture_height * 4/5), 
        (picture_width/5), 
        (picture_height/5) ] 
    }); 
} 

function stopJcrop() { 
    jcrop_api.destroy(); 
    return (false); 
} 

/* Example in use */ 

$('#start_button').bind('click', function() { 
    $('#image_file').attr('src', server_file); 
    initJcrop('raw_file'); 
}); 

$('#end_button').bind('click', function() { 
    stopJcrop(); 
}); 
13

me he encontrado con esta situación. Puse mi jcropimage (#cropbox) en un div y simplemente vacié el html del div. Ver código de abajo

javascript:



try { 
    $("#workspace").html(''); 
    } catch (Error) 
    { } 

//add cropbox on the fly 
$("#workspace").prepend(//create img tag with id "cropbox" here... i can't seem to post my code - Stack Overflow mechanism); 
$('#cropbox').attr("src", 'path/to/image'); 
$('#cropbox').Jcrop(); 

Espero que esto ayude.

+0

Esta es una buena respuesta . Simple y efectivo. +1 –

+0

Esta solución realmente me salvó la vida, muchas gracias. –

+0

Esto es lo único que lo salvará si desea actualizar el panel de vista previa, incluso en 2014. Muchas gracias. – Hendrik

31

última versión tiene la función setImage

http://deepliquid.com/projects/Jcrop/js/jquery.Jcrop.js

var jcrop_api; 
$().ready(function() { 
      initJcrop(); 
      function initJcrop() 
      { 
       jcrop_api = $.Jcrop('#cropbox'); 
      }; 
}); 

luego llamar a

jcrop_api.setImage('server/uploads/image.jpg'); 

Theres un ejemplo aquí

http://deepliquid.com/projects/Jcrop/demos/tutorial5.html

+4

La firma es 'function setImage (src, callback)' para que pueda tener una devolución de llamada cuando la imagen termine de cargarse. y la creación de API está privada. Usa esto en su lugar 'var jcrop_api; $ ('# destino'). Jcrop (opciones, función() { jcrop_api = esto; }); ' – ppumkin

+0

Tenga cuidado,' var api = $ ('img'). Jcrop (opciones) 'will ** no funciona ** use '$ .Jcrop ($ ('img') [0], opciones)' en su lugar (ref: http: //deepliquid.com/content/Jcrop_API.html) –

+0

Para evitar que el navegador guarde en caché la imagen : jcrop_api.setImage (filename + '?' + d.getTime()); – Alex2php

0

Termino con este problema también. Si agrego y elimino la imagen de la caja de cultivo todo funciona bien.

............ 
$("#wrapper").on('click', '.img-crop-trigger',function(e){ 
    //clear the wrapper 
    $("#cropImageWrp").html(""); 
    // add the image cropbox 
    $("#cropImageWrp").append("<img src='' id='cropbox'>"); 
    //set the image source 
    $("#cropbox").attr("src", "/"+imageToCropUrl); 
............................... 
1

La solución más sencilla que he encontrado:

$('.jcrop-holder img').attr('src', 'new image url'); 
2

Si desea cambiar la imagen/recarga con jcrop usted tiene que utilizar una función setImage():

//create var 
var jscrop_api; 

//set instance to our var 
$('#cropping-image').Jcrop({ 
     onChange: setCoords, 
     onSelect: setCoords 
}, function() { jcrop_api = this; }); 

//change image for instance 
jcrop_api.setImage("newPhoto.png"); 
Cuestiones relacionadas