Accede a tu zona privada
Jaime MM

Emular el efecto multiplicar con jQuery

Efecto multiplicar con jQuery

Efecto multiplicar con jQuery

12 septiembre, 2015   |   Jaime MM

– Nota –
Lo bueno (y lo malo) de nuestro trabajo es que todos los días aprendemos algo nuevo, no? Bueno, pues resulta que con CSS se puede hacer algo muy chulo. Las líneas son las siguientes

js
  1. mix-blend-mode: multiply;
  2. background-blend-mode: multiply;

y aplicadas sobre una capa con background color (alpha o no) nos permiten utilizar el efecto mutiplicar sin jquery ni nada parecido. Dicho esto, el artículo sigue teniendo toda la utiliza del mundo por si acaso. Todos sabemos de lo que estamos hablando, verdad?
– Fin de nota –

 

Desde hace mucho tiempo, y demasiadas veces, los diseñadores web con los que trabajo me han pedido que traslade la transparencia que consiguen con su amado Photoshop y el efecto multiplicar a los navegadores. La solución que aplicaba ha ido variando con el tiempo empezando por los pngs con transparencia al 10% encima de la imagen y terminando con el rgba de CSS3.

Pero la última vez que me pasó, se me ocurrió pensar que gracias a HTML5 y Canvas quizás se podría intentar algo un poco mejor. Y resulta que se puede. El resultado es espectacular, similar al de Photoshop, pero con programación y sujeto a las variables que necesitemos.

Ahora, vamos a ver el código que necesitamos:

js
  1. /// Colores que vamos a aplicar en forma de array RGB
  2. color_multiplicar_1=[230, 148, 184];
  3. color_multiplicar_2=[126, 115, 55];
  4. /// Indice de las imágenes tratadas
  5. indice_canvas=1;
  6.  
  7. /// Función que calcula el valor correcto para cada canal
  8. function multiplicar (valor_max, valor_min){
  9. return valor_max * valor_min / 255;
  10. }
  11. /// La función duplica la imagen que se le pasa en el primer parámetro
  12. function duplica_imagen_multiplicar (imagen, indice) {
  13. /// Creamos el canvas con el nombre que nos interesa (en este caso utilizamos el índice)
  14. eval("canvas_"+indice+" = document.createElement('canvas');"); /// Creamos el canvas
  15. eval("canvas_"+indice+".width = $(imagen).width();");
  16. eval("canvas_"+indice+".height = $(imagen).height();");
  17. /// Creamos el canvas con el nombre que nos interesa (en este caso utilizamos el índice)
  18. /// Creamos la imagen que va a lanzar todo el proceso
  19. var img = document.createElement('img');
  20. img.src=$(imagen).attr("src");
  21. $(img).attr("data",indice);
  22. $(img).attr("rel",$(imagen).attr("rel"));
  23. img.onload = function() {
  24. ctx = eval("canvas_"+indice+".getContext('2d');");
  25. ctx.drawImage(this, 0, 0);
  26. /// Aquí es donde, según la class de la imagen, yo le aplico un color u otro. En este caso aplicaremos el mismo siempre
  27. if (indice==1) colores_temporales=color_multiplicar_1;
  28. else colores_temporales=color_multiplicar_2;
  29. /// Obtenemos los datos de la imagen
  30. info_imagen = ctx.getImageData(0, 0, eval("canvas_"+indice+".width"), eval("canvas_"+indice+".height"));
  31. pix = info_imagen.data;
  32. /// Recorremos los pixels
  33. for (var i = 0, n = pix.length; i < n; i += 4) {
  34. pix[i ] = multiplicar(colores_temporales[0], pix[i ]); // red
  35. pix[i+1] = multiplicar(colores_temporales[1], pix[i+1]); // green
  36. pix[i+2] = multiplicar(colores_temporales[2], pix[i+2]); // blue
  37. //pix[i+3] es el canal alpha que, en este caso, vamor a ignorar
  38. }
  39. /// Volcamos el resultado al canvas
  40. ctx.putImageData(info_imagen, 0, 0);
  41. }
  42. }
  43. /// Llamamos a la creación de la imagen
  44. jQuery("#imagen_pruebas_multiplicar").ready(function () {
  45. setTimeout(function () {
  46. duplica_imagen_multiplicar(jQuery("#imagen_pruebas_multiplicar"),indice_canvas);
  47. /// Ya tenemos el canvas, ahora lo añadimos a la capa que contiene la imagen normal para ver la diferencia
  48. jQuery("#imagen_pruebas_multiplicar").parent().append("
  49.  
  50. ").append(eval("canvas_"+indice_canvas)); /// Añadimos el canvas
  51. duplica_imagen_multiplicar(jQuery("#imagen_pruebas_multiplicar"),++indice_canvas);
  52. /// Ya tenemos el canvas, ahora lo añadimos a la capa que contiene la imagen normal para ver la diferencia
  53. jQuery("#imagen_pruebas_multiplicar").parent().append("
  54.  
  55. ").append(eval("canvas_"+indice_canvas)); /// Añadimos el canvas
  56. }, 500);
  57. });

Y aquí está el resultado:

 

Espero de verdad que os sea de utilidad y os haya gustado. La semana que viene más!!

Share Button
Escrito por Author Jaime MM

    3.592 Comments

  1. Four score and seven minutes ago, I read a sweet artelci. Lol thanks

    Joni

    13 abril, 2016

  2. A bit surprised it seems to simple and yet useful.

    car insurance

    15 abril, 2016

  3. With the bases loaded you struck us out with that answer!

    car insurance

    15 abril, 2016

  4. I don’t know who you wrote this for but you helped a brother out.

    cheap car insurance

    15 abril, 2016

  5. I’m not quite sure how to say this; you made it extremely easy for me!

    auto insurance quotes

    15 abril, 2016

  6. I’m not worthy to be in the same forum. ROTFL

    auto insurance

    16 abril, 2016

  7. I love these articles. How many words can a wordsmith smith?

    insurance auto

    16 abril, 2016

  8. Unparalleled accuracy, unequivocal clarity, and undeniable importance!

    car insurance rates

    16 abril, 2016

  9. Boy that really helps me the heck out.

    insurance car

    16 abril, 2016

  10. I told my grandmother how you helped. She said, “bake them a cake!”

    cheapest car insurance

    16 abril, 2016

  11. This is an article that makes you think “never thought of that!”

    insurance car

    16 abril, 2016

  12. That addresses several of my concerns actually.

    car insurance

    16 abril, 2016

  13. Reading this makes my decisions easier than taking candy from a baby.

    car insurance quotes

    17 abril, 2016

  14. I like to party, not look articles up online. You made it happen.

    insurance auto

    17 abril, 2016

  15. I’m shocked that I found this info so easily.

    auto insurance

    17 abril, 2016

  16. The answer of an expert. Good to hear from you.

    car insurance

    17 abril, 2016

  17. If your articles are always this helpful, “I’ll be back.”

    auto insurance

    17 abril, 2016

  18. You’ve got it in one. Couldn’t have put it better.

    car insurance

    17 abril, 2016

  19. Great insight. Relieved I’m on the same side as you.

    auto insurance FL

    17 abril, 2016

  20. That insight solves the problem. Thanks!

    auto insurance

    17 abril, 2016

  21. Your posting is absolutely on the point!

    car insurance

    17 abril, 2016

  22. That’s a well-thought-out answer to a challenging question

    DC cheap insurance

    18 abril, 2016

  23. Everyone would benefit from reading this post

    auto insurance

    18 abril, 2016

  24. I told my kids we’d play after I found what I needed. Damnit.

    insurance car

    18 abril, 2016

  25. Deadly accurate answer. You’ve hit the bullseye!

    insurance car

    18 abril, 2016

  26. That’s really thinking at an impressive level

    auto insurance

    18 abril, 2016

  27. I’m out of league here. Too much brain power on display!

    car insurance

    18 abril, 2016

  28. Your post has lifted the level of debate

    car insurance

    18 abril, 2016

  29. Articles like this are an example of quick, helpful answers.

    car insurance

    18 abril, 2016

  30. Why does this have to be the ONLY reliable source? Oh well, gj!

    car insurance online

    18 abril, 2016

  31. And I thought I was the sensible one. Thanks for setting me straight.

    online car insurance

    18 abril, 2016

  32. Articles like these put the consumer in the driver seat-very important.

    insurance in Delaware

    19 abril, 2016

  33. You have more useful info than the British had colonies pre-WWII.

    cheap auto insurance

    19 abril, 2016

  34. In the complicated world we live in, it’s good to find simple solutions.

    auto insurance quotes

    19 abril, 2016

  35. Knowledge wants to be free, just like these articles!

    cheap insurance

    19 abril, 2016

  36. Extremely helpful article, please write more.

    insurance car

    19 abril, 2016

  37. That’s the best answer by far! Thanks for contributing.

    insurance auto

    19 abril, 2016

  38. Shiver me timbers, them’s some great information.

    insurance auto

    19 abril, 2016

  39. Keep these articles coming as they’ve opened many new doors for me.

    insurance car

    19 abril, 2016

  40. I came, I read this article, I conquered.

    car insurance

    19 abril, 2016

  41. With all these silly websites, such a great page keeps my internet hope alive.

    car insurance quotes

    19 abril, 2016

  42. It’s spooky how clever some ppl are. Thanks!

    cheap insurance

    19 abril, 2016

  43. Just what the doctor ordered, thankity you!

    auto insurance

    19 abril, 2016

  44. That insight’s perfect for what I need. Thanks!

    car insurance

    19 abril, 2016

  45. If I communicated I could thank you enough for this, I’d be lying.

    car insurance online

    20 abril, 2016

  46. Apparently this is what the esteemed Willis was talkin’ ’bout.

    insurance car

    20 abril, 2016

  47. At last! Someone with real expertise gives us the answer. Thanks!

    insurance auto

    20 abril, 2016

  48. Times are changing for the better if I can get this online!

    car insurance

    20 abril, 2016

  49. An intelligent answer – no BS – which makes a pleasant change

    car insurance quotes

    20 abril, 2016

  50. Great article but it didn’t have everything-I didn’t find the kitchen sink!

    car insurance rates

    20 abril, 2016

  51. I am totally wowed and prepared to take the next step now.

    car cheap insurance

    20 abril, 2016

  52. There’s nothing like the relief of finding what you’re looking for.

    cheap auto insurance

    20 abril, 2016

  53. Thanks for sharing. What a pleasure to read!

    car insurance

    21 abril, 2016

  54. That’s a slick answer to a challenging question

    car insurance

    21 abril, 2016

  55. Clear, informative, simple. Could I send you some e-hugs?

    car insurance rate

    21 abril, 2016

  56. This is the perfect way to break down this information.

    car insurance

    21 abril, 2016

  57. Intelligence and simplicity – easy to understand how you think.

    cheap insurance

    22 abril, 2016

  58. Walking in the presence of giants here. Cool thinking all around!

    cheap auto insurance

    22 abril, 2016

  59. This is what we need – an insight to make everyone think

    auto insurance

    22 abril, 2016

  60. What a pleasure to find someone who identifies the issues so clearly

    car insurance

    22 abril, 2016

  61. And to think I was going to talk to someone in person about this.

    car insurance online

    22 abril, 2016

  62. Mighty useful. Make no mistake, I appreciate it.

    car insurance

    22 abril, 2016

  63. Furrealz? That’s marvelously good to know.

    car insurance

    23 abril, 2016

  64. Please teach the rest of these internet hooligans how to write and research!

    car insurance rates OK

    23 abril, 2016

  65. I’m not easily impressed but you’ve done it with that posting.