Spatial Filters
When working with pixels we don't have to work only with the pixel we're looking at directly, we can work with pixels around the pixel we're currently looking at in the loop.
A common way to do this is to use what's called a spatial filter (or kernerl). Take a look at this image:
Here we see 2 kernels for filtering an image. If you multiply the values for the kernel on the left you would get a 3x3 grid of 1/9 values (all would be the same). This is called a Box Blur filter.
The filter on the right resembles a Gaussian Blur filter, a blur that resembles a soft brush from photoshop (thick in the center and softer at the edges).
Imagine taking a line of pixels like the ones above and applying a Box Blur filter. The pixel in the middle (black) would become lighter (influenced by the surrounding white pixels), and the neighboring pixels (white) would become darker (influenced by the middle pixel).
A gaussian blur will have the same result but maintain more of the color of the pixel in the center of the filter.
Let's take a look at how to apply a kernel:
//loop all pixels for (var i = 0; i < data32; i++) { //kernelX will keeps track of kernel position var r = 0, g = 0, b = 0, kernelX = -1; //loops -1, 0, 1 for (var j = -1; j < 2; j++) { kernelX++; var kernelY = -1; //loops -1, 0, 1 for (var k = -1; k < 2; k++) { kernelY++; //get pixel @ current kernel position var index = i + k * w + j; var pixel = data32[index]; //do an operation using kernel value rx += ((pixel) & 0xff) * kernel[kernelX][kernelY]; //... more operations } } }
Transformations
This should largely be a review but we will be working working with a few CSS transformations to manipulate our canvas around the screen. They are:
- Translate X Y Z
- Scale X Y
- Rotate X Y Z
There is another factor in using CSS 3D Transformations and that is Perspective which controls how "deep" the 3D effect will be. A smaller perspective value means a deeper perspective, larger means more shallow.
You can set the transform of any html element using the following code:
//get canvas and controls var canvas = this.canvas, tranX = this.controls.TranslateX.value, tranY = this.controls.TranslateY.value, tranZ = this.controls.TranslateZ.value, scaleX = this.controls.ScaleX.value, scaleY = this.controls.ScaleY.value, rotX = this.controls.RotateX.value, rotY = this.controls.RotateY.value, rotZ = this.controls.RotateZ.value, perspective = this.controls.Perspective.value; //NOTE canvas is not an html5 canvas element but a JS Object //canvas property element is the actual html5 canvas element canvas.element.style.transform = 'perspective(' + perspective + 'px) ' + 'translate3d(' + tranX + 'px, ' + tranY + 'px, ' + tranZ + 'px) ' + 'scale(' + scaleX + ', ' + scaleY + ') ' + 'rotateX(' + rotX + 'deg) rotateY(' + rotY + 'deg) rotateZ(' + rotZ + 'deg)';
*** Only tested in Chrome (latest version)