Román Cortés

Merry Christmas

27 de Diciembre del 2009

Click here to see the effect

 CLICK HERE TO SEE THE EFFECT!

(versión en castellano abajo)

First of all: Merry Christmas and Happy New Year!

 Today I’ve done a 3D snowman in Javascript. I decided to do something Christmas-related and also to try the canvas element and the direct pixels color-value control with createImageData and putImageData.

So, just before the web gets truly 3D with standards like WebGL, I thought it would be cool to try the oldschool cpu software rendering in Javascript. Would it be possible? Could I even do some kind of lightning? The answer is yes: but it required a lot of tricks and even with those, a fast computer to render at a reasonable framerate. Javascript continues being very slow for things like this one.

 What I did: parallel sphere raycasting with some modifyed/simplified SSAO (screen space ambient occlussion).

Just a little note: This is a one-file effect, there are no textures or whatever, and everthing fits in only 4kb.

UPDATE: Thanks so much to p01 - an expert javascript coder and part of the Opera browser team - for suggesting the change from createImageData(widht, height) to getImageData(0, 0, width, height). Now it works in more versions of browsers.

Castellano

Ante todo: ¡Feliz Navidad y próspero año nuevo!

Hoy he hecho este muñeco de nieve en 3D con Javascript. Decidí hacer algo navideño y también probar el elemento canvas (aún no había hecho nada porque suelo inclinarme más por efectos totalmente crossbrowser) y el manejo de color de píxeles directo que proporcionan createImageData y putImageData.

Antes de que la web se vuelva totalmente 3D gracias a futuros estándares como WebGL, pensé que estaría bien intentar algo de renderizado a la antigua usanza, usando la cpu en Javascript. ¿Sería posible? ¿Podría agregar algún tipo de iluminación? La respuesta es sí: pero ha requerido bastantes trucos y aún así necesita un ordenador bastante potente para mostrar suficientes imágenes por segundo. Javascript sigue siendo un poco lento para estos fines.

Lo que hice: trazado de rayos no recursivo para esferas e iluminación SSAO (Oclusión ambiental aproximada basada en el buffer de profundidad), modificada/simplicada para mi efecto.

Una pequeña nota: este efecto está contenido al completo en un único fichero html, no hay texturas ni similar, y todo ocupa sólo 4kb.

Javascript Text Reflection

22 de Diciembre del 2009

(versión en castellano abajo)

Today I’ve done this little Javascript experiment that makes an Apple-style reflection on html text - without images. It is extremely simple: it just cuts the text in 1px horizontal lines and place these in inverse/reflected order.

The “Write here!” is an input field, so you can click on it, change the text and see how the effect dynamically changes the reflection.

It works in IE 8, 7, 6 and - magically - in 5.5. It have been tested and it is working also in Firefox 3.5, Firefox 2, Konqueror 3, Opera 9, Safari 3 and Chrome 4.

Note: please remember that this is just a fun experiment and not thought to be useful in any way. If you are going to use it in your website, think that it is probably going to cause accessibility problems on javascript enabled text-only, text-to-voice and text-to-braille browsers, so I can’t recommend its use on any serious/non-experimental websites.

Castellano

Hoy he realizado este pequeño experimento con Javascript que crea reflejo sobre texto html al estilo Apple (sin usar imágenes). El funcionamiento es muy simple: el texto se corta a líneas horizontales de 1 pixel y las pongo en orden inverso/reflejado.

Donde pone “Write here!” (traducido: ¡Escribe aquí!) hay realmente un campo de texto. Podéis pinchar, cambiar dicho texto y ver cómo el efecto de reflejo cambia dinámicamente mientras se escribe. El botón de “Shake it!” menea</e el texto reflejado.

Funciona en todos los navegadores que he podido probar, incluyendo asombrosamente (¿o mágicamente?) el Internet Explorer 5.5.

Nota: este efecto es sólo un experimento por diversión, y no se debería tomar como algo útil de ninguna forma. Si alguien se piensa usarlo en alguna página, que recuerde que puede causar problemas graves de accesibilidad para personas que usen navegadores con javascript en modo de sólo texto, lectores de voz de páginas web y lectores web braille. Por tanto, no puedo recomendar su uso en prácticamente ninguna web, a excepción de webs experimentales y poco más.

3D Meninas explained

17 de Diciembre del 2009

A lot of people is asking me how my Pure CSS 3D Meninas effect works and how I did it. In this post I will try to fully explain it, from the image edition part to the html/css coding part. Even if this is going to look like a tutorial, please, don’t take it as a tutorial; this effect is just an experiment and not thought to be useful or a good practice in web design.

Bastantes personas me han pedido que explique cómo hice y cómo funciona mi efecto 3D de las Meninas con CSS. En este post voy a intentar explicarlo al completo, empezando por la edición de imágenes y terminando con la parte de código html y css. Por favor, no toméis esto como un tutorial; va a parecerlo, pero el efecto es sólo un experimento y no está pensado para que sea útil ni una buena práctica de diseño web.

Finding the vanishing point / Encontrando el punto de fuga

Trace 2 lines (in green) following the 3d parallel lines in the right wall until they cross. The crossing point (in yellow) is the vanishing point. Trace two lines following the right and bottom corners of the back wall (in red). A line crossing the vanishing point and the intersection of the two red lines (in blue) defines the corner of the ground with the right wall.

Traza dos líneas (en verde) siguiendo las paralelas en 3d de la pared de la derecha hasta que se crucen. El punto de cruce (en amarillo) es el punto de fuga. Traza dos líneas siguiendo las esquinas inferior y derecha de la pared del fondo (en rojo). Una línea que pasa por el punto de fuga y la intersección entre las líneas en rojo (en azul) define la esquina que forma el suelo con la pared derecha.

Layers’ movement speed / Velocidad de movimiento de las capas

When moving the layers to make the parallax effect by displacing the vanishing point as in my effect, the relative speed of these is inversely proportional to the height from the vanishing point to the ground. The red horizontal lines are proportional in width to this height too (Intercept theorem), and I believe it is easier to see it this way. If you want to move the viewer instead the vanishing point, the speed would be directly proportional instead of inversely.

Al mover las capas para crear el efecto 3d parallax, la velocidad de cada capa ha de ser inversamente proporcional a su distancia vertical desde el punto de fuga al suelo. En la imagen, las líneas rojas horizontales son proporcionales en largo a esta distancia (primer teorema de Tales), y creo que así se entiende bastante mejor. Si en vez de mover el punto de fuga, moviésemos al espectador, la velocidad de las capas sería proporcional en vez de inversamente proporcional.

Cutting the images / Recortando las capas

This is the part that takes more time: cut a layer and place it apart, fill the holes, cut another layer, and so on. Obviously it is not required to paint parts of the image that are going to be occluded in the effect.

Esta es la parte en la que se tarda más: corta una capa y déjala aparte, rellena los huecos, corta otra capa y así. Obviamente no es necesario pintar las partes de la imagen que van a quedarse ocultas en el efecto.

CSS Sprites / Sprites CSS

In this example I’ve used the CSS sprites technique, wich consists in making a big image containing different images, and then show these cutted by CSS. By reducing the number of files a website have to request to the server, the loading time get decreased. The layers look like this:

En este ejemplo he usado la ténica de sprites CSS.

So, how to make a CSS Sprite? Use a block element with the sprites file as background-image, with the width and height of the sprite you want to take, and background-position defining the offset of it in the whole sprites image. Remember that the background positions should be negative.

¿Cómo hacer un sprite CSS? Usa un element block al que le asignas de background-image el fichero de sprites, con el ancho y alto del sprite que quieras tomar y de backgrond-position la distancia hasta la esquina superior izquierda de la imagen de sprites completa. Recuerda que las posiciones del fondo deben ser negativas.

<div style=”background-image: url(’meninas-sprites.png’); width: 205px; height: 128px; background-position: -23px -120px”></div>

Complex hover effects / Efectos complejos de hover

Current browsers support complex hover effects for all tags and allow changes in child tags caused by the hover of the parent tag. Let’s take a look of the following code:

HTML:

<a href=”#” mce_href=”#”><img src=”something.jpg” mce_src=”something.jpg” />Some text here <span>and more text here</span></a>

CSS:

a img {position: absolute; top: 500px; left: 300px;}
a:hover img {top: 400px;}
a:hover span {font-weight: bold;}

With this code, when hovering the <a> element, the image with change of position, and the text between the <span> tag will change its weight to bold. As you can see, it is easy to make really complex hovers modifying different properties of different elements inside the main hovered tag.

Los navegadores actuales soportan efectos complejos de hover para todas las etiquetas y permiten cambios en etiquetas hijo causadas por el hover de etiquetas padre.

En el ejemplo, al pasar el ratón por el elemento <a>, la imagen que contiene cambiará de posición y el texto contenido en el <span> cambiará a negrita. Como veréis, se pueden crear de esta forma efectos bastante complejos, modificando propiedades de diferentes elementos dentro de la etiqueta que causa el hover.

How the layers move by the mouse position? / ¿Cómo se mueven las capas según las posición del ratón?

There are 80 vertical hover elements of 5*455 pixels each, covering the full effect. Each hover element contains inside elements to define every layer position, the background image and the lateral background image. When the hover element is not active (without the mouse over it), all is inside elements showing images are hidden, with display: none.

When the hover element is active, the images are set to display: block, and the position of these are set. These positions have been calculated and are written in the CSS code for each layer and each of the 80 vertical hover elements. This is what does the magic.

Since the hovering elements are overlapping, there is a little problem to do this, because once the element is hover and shows its inside images, all the area is part of the hover, so it will not switch to other hover element until you move your mouse outside the effect.

So, how to make it work? The solution I found was to use z-indexs and spans with   on top of the images. This looks to work fine with all the current browsers.

Hay 80 elementos verticales con hover de 5*455 píxeles cada uno, cubriendo así todo el area del efecto. Cada uno contiene elementos internos que definen la posición de cada capa, la imagen de fondo y la imagen lateral de fondo. Cuando el hover no está activo, todos los elementos internos con imágenes están ocultos con display: none.

Cuando el hover está activo, las imágenes aparecen como display: block y en sus posiciones correspondientes. Estas posiciones han sido calculadas y están escritas en el código CSS directamente, para cada capa y para cada uno de los 80 elementos con hover. Esto es lo que “hace la magia”.

Hay un problema en esto porque los elementos se superponen. Al activar el hover y mostrarse las imágenes, el navegador considera que todo el area pertenece a ese hover y no se puede cambiar de un hover a otro. La solución que encontré fue hacer una mezcla de z-indexs y spans con   de forma que las areas de hover siempre permanezcan por encima de las imágenes. Esto parece que funciona bien en todos los navegadores actuales.

Right background lateral / El lateral derecho del fondo

A true parallax effect would be not only 4 or 5 layers, but a layer for every vertical 1-pixel-height line on the ground/ceiling. This would be 2 or 3 hundreds of layers. The html/css code for it would be a lot of bigger, and also the browsers would not be able to render it in a decent speed.

So, I had to find a way to make it look reasonably good but with a simpler way, so what I did was to divide the background in two parts:

Then, while the first image is only displaced, the second image with the right lateral is displaced and resized. You can not resize CSS sprites or background-images, but you can resize <img> elements by setting the width and height desired.

Un verdadero efecto de parallax no hubiese sido de sólo 4 o 5 capas, sino de una capa por cada pixel de altura del suelo/techo; 200 o 300 capas. El código html/css para ello sería muchísimo mayor, y los browsers actuales no podrían renderizarlo a una velocidad aceptable. Por tanto, tuve que buscar una forma con la que se viese lo suficientemente bien el efecto pero fuese más simple. Lo que hice fue dividir el fondo en dos partes, tal y como se ve en las imágenes superiores.

Mientras la primera imagen sólo se desplaza, la segunda imagen de la pared de la derecha se desplaza y también se redimensiona. No se puede redimensionar los sprites CSS, pero sí que se puede redimensionar los elementos <img> asignándoles el ancho y alto deseado.

Source code / código fuente

Some people asked me for the php script I used to generate the html. I consider it is not very valuable but… here it is.

Varias personas me han pedido que muestre el código en php que usé para generar el html. No creo que sea demasiado interesante pero… aquí lo tenéis.

CSS 3D Meninas

14 de Diciembre del 2009

(versión en castellano abajo)

I’ve took the classic paint The Maids of Honour (Las Meninas) and made this CSS pseudo-3D/parallax effect. It is pure CSS, so no javascript or flash involved: only CSS and HTML code.

It has been tested and it is working on Internet Explorer 8, Firefox 3, Opera 9, Safari 3, Chrome 4 and Konqueror 3.5, and it validates.

UPDATE: 3D Meninas Explained

Castellano

He tomado el cuadro Las Meninas y he creado este efecto pseudo-3D con CSS. Es CSS puro, sin javascript ni flash; sólo código CSS y HTML.

Para la realización he usado tres imágenes: dos se corresponden al fondo (paredes) y otra de sprites (3 sprites: uno con el lienzo, niño y perro, otro con las meninas, y el último con la monja y acompañante). El posicionamiento de los sprites se realiza mediante hover en un total de 80 anchors. El lateral derecho de la habitación se ensancha y contrae para mejorar el efecto 3D.

Hay algunos truquitos para que el hover funcione correctamente, podéis verlos en el código fuente. Para que no interfieran las imáges en el hover, he usado distintos z-indexs y nbsps con tamaño de fuente de 455 píxeles: el mismo alto que el experimento en sí.

Funciona en las últimas versiones de los navegadores más usados y valida.

UPDATE: Explicación del efecto