Understanding how canvas converts an image to black and white - javascript

I found this script for converting an image to black and white, which works great, but I was hoping to understand the code a little bit better. I put my questions in the code, in the form of comments.
Can anyone explain in a little more detail what is happening here:
function grayscale(src){ //Creates a canvas element with a grayscale version of the color image
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var imgObj = new Image();
imgObj.src = src;
canvas.width = imgObj.width;
canvas.height = imgObj.height;
ctx.drawImage(imgObj, 0, 0); //Are these CTX functions documented somewhere where I can see what parameters they require / what those parameters mean?
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
var i = (y * 4) * imgPixels.width + x * 4; //Why is this multiplied by 4?
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3; //Is this getting the average of the values of each channel R G and B, and converting them to BW(?)
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}

The canvas functions are, like most functions, described in an official specification. Also, MDC is helpful for more "informal" articles. E.g. the drawImage function on MDC is here.
The getImageData function returns an object, which contains an array with the byte data of all pixels. Each pixel is described by 4 bytes: r, g, b and a.
r, g and b are the color components (red, green and blue) and alpha is the opacity. So each pixel uses 4 bytes, and therefore a pixel's data begins at pixel_index * 4.
Yes, it's averaging the values. Because in the next 3 lines r, g and b are all set to that same value, you'll obtain a gray color for each pixel (because the amount of all 3 components are the same).
So basically, for all pixels this will hold: r === g, g === b and thus also r === b. Colors for which this holds are grayscale (0, 0, 0 being black and 255, 255, 255 being white).

function grayscale(src){ //Creates a canvas element with a grayscale version of the color image
//create canvas
var canvas = document.createElement('canvas');
//get its context
var ctx = canvas.getContext('2d');
//create empty image
var imgObj = new Image();
//start to load image from src url
imgObj.src = src;
//resize canvas up to size image size
canvas.width = imgObj.width;
canvas.height = imgObj.height;
//draw image on canvas, full canvas API is described here http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html
ctx.drawImage(imgObj, 0, 0);
//get array of image pixels
var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
//run through all the pixels
for(var y = 0; y < imgPixels.height; y++){
for(var x = 0; x < imgPixels.width; x++){
//here is x and y are multiplied by 4 because every pixel is four bytes: red, green, blue, alpha
var i = (y * 4) * imgPixels.width + x * 4; //Why is this multiplied by 4?
//compute average value for colors, this will convert it to bw
var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
//set values to array
imgPixels.data[i] = avg;
imgPixels.data[i + 1] = avg;
imgPixels.data[i + 2] = avg;
}
}
//draw pixels according to computed colors
ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
return canvas.toDataURL();
}
In this function coefficient equal to 1/3 are used, however the usually used are: 0.3R + 0.59G + 0.11B (http://gimp-savvy.com/BOOK/index.html?node54.html).

Related

Canvas Pixelation - Adjust pixel size

I've got a script that cycle's through images. The images start pixelated and then when they are in view, become unpixelated. I achieve that by calling this function x amount of times with requestAnimationFrame
Images.prototype.setPixels = function() {
var sw = this.imageWidth,
sh = this.imageHeight,
imageData = this.context.getImageData( 0, 0, sw, sh ),
data = imageData.data,
y, x, n, m;
for ( y = 0; y < sh; y += this.pixelation ) {
for ( x = 0; x < sw; x += this.pixelation ) {
var red = data[((sw * y) + x) * 4];
var green = data[((sw * y) + x) * 4 + 1];
var blue = data[((sw * y) + x) * 4 + 2];
for ( n = 0; n < this.pixelation; n++ ) {
for ( m = 0; m < this.pixelation; m++ ) {
if ( x + m < sw ) {
data[((sw * (y + n)) + (x + m)) * 4] = red;
data[((sw * (y + n)) + (x + m)) * 4 + 1] = green;
data[((sw * (y + n)) + (x + m)) * 4 + 2] = blue;
}
}
}
}
}
this.context.putImageData( imageData, 0, 0 );
}
Question: How can I make the individual pixels larger blocks than they are right now. Right now they are pretty small, and the effect is a little jarring. I'm hoping to fix this by having less pixel blocks on the screen, by making them bigger.
I hope this makes sense, I'm fairly green with canvas, so anything you could do to point me in the right direction would be great!
The best for this kind of effect is to simply use drawImage and let the browser handle the pixelation thanks to the nearest-neighbor anti-aliasing algorithm that can be set by changing the imageSmoothingEnabled property to false.
It then becomes a two step process to pixelate an image at any pixel_size:
draw the full quality image (or canvas / video ...) at its original size / pixel_size.
At this stage, each "pixel" is one pixel large.
draw this small image again but up-scaled by pixel_size. To do so, you just need to draw the canvas over itself.
Each pixel is now pixel_size large.
Instead of dealing with hard to read many parameters of drawImage, we can deal the scaling quite easily by just using ctx.scale() method.
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function drawPixelated( source, pixel_size ) {
// scale down
ctx.scale(1 / pixel_size, 1 / pixel_size)
ctx.drawImage(source, 0, 0);
// make next drawing erase what's currently on the canvas
ctx.globalCompositeOperation = 'copy';
// nearest-neighbor
ctx.imageSmoothingEnabled = false;
// scale up
ctx.setTransform(pixel_size, 0, 0, pixel_size, 0, 0);
ctx.drawImage(canvas, 0, 0);
// reset all to defaults
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalCompositeOperation = 'source-over';
ctx.imageSmoothingEnabled = true;
}
const img = new Image();
img.onload = animeLoop;
img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
let size = 1;
let speed = 0.1;
function animeLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
size += speed;
if(size > 30 || size <= 1) {
speed *= -1
}
drawPixelated( img, size );
requestAnimationFrame(animeLoop);
}
<canvas id="canvas" width="800" height="600"></canvas>
Now for the ones that come with a real need to use an ImageData, for instance because they are generating pixel-art, then know that you can simply use the same technique:
put your ImageData with each pixel being 1 pixel large.
scale your context to pixel_size
draw your canvas over itself upscaled
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function putPixelated( imageData, pixel_size ) {
ctx.putImageData(imageData, 0, 0);
// make next drawing erase what's currently on the canvas
ctx.globalCompositeOperation = 'copy';
// nearest-neighbor
ctx.imageSmoothingEnabled = false;
// scale up
ctx.setTransform(pixel_size, 0, 0, pixel_size, 0, 0);
ctx.drawImage(canvas, 0, 0);
// reset all to defaults
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalCompositeOperation = 'source-over';
ctx.imageSmoothingEnabled = true;
}
const img = new ImageData(16, 16);
crypto.getRandomValues(img.data);
let size = 1;
let speed = 0.1;
animeLoop();
function animeLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
size += speed;
if(size > 30 || size <= 1) {
speed *= -1
}
putPixelated( img, size );
requestAnimationFrame(animeLoop);
}
<canvas id="canvas" width="800" height="600"></canvas>

Get color from array returned by canvas.getImageData() method

I have a canvas and want to dynamically get the color of a pixel. Im using getImageData() to get an array containing the colors. I only want to call getImageData() once and get all the color data from it once. This is because in my use case I will loop over an array of size 1 million containing of x, y coordinates for the canvas.
However I cannot figure out how to get the color from the image array with the x, y coordinates. Here's my code:
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
context.beginPath();
context.rect(0, 0, 200, 200);
context.fillStyle = 'black';
context.fill();
context.closePath();
context.beginPath();
context.rect(50, 50, 50, 50);
context.fillStyle = 'red';
context.fill();
context.closePath();
var imageData = context.getImageData(0, 0, 200, 200).data;
console.log('imageData is ', imageData);
for(var x = 0; x < 10; x++) {
var x = Math.floor(Math.random() * 200);
var y = Math.floor(Math.random() * 200);
console.log('x, y is ', x, y);
// how to I get the color here?
var color = Uint8ClampedArray[x][y];
console.log('color is ', color);
}
I get an error at the line:
var color = Uint8ClampedArray[x][y];
All other solutions involve calling getImageData() each time on the coordinate with a width and height of 1. But I dont want to do this, preferring to query imageData to get the color....
Fiddle is here.
To get a pixel
var x = 100;
var y = 100;
var imageData = context.getImageData(0, 0, 200, 200);
var index = (x + y * imageData.width) * 4;
var r = imageData.data[index];
var g = imageData.data[index + 1];
var b = imageData.data[index + 2];
var a = imageData.data[index + 3];
There are 4 bytes per pixel, pixels are arranged in rows. So each row has 4 * the width bytes.
Thus you find the row or y
var rowStart = y * imageData.width * 4;
and to find the pixel at column x multiply by 4 and add to the start row index
var pixelIndex = rowStart + x * 4;
The next 4 bytes are the red, green, blue and alpha values of the pixel at x,y

Image alpha on default Android browser

I'm trying to duotone an image and plaster it onto a canvas.
Works in desktop browsers:
Chrome
Firefox
Safari
Internet Explorer
Fails in mobile browsers:
Android
Workable demo on JSFiddle, this example works in Chrome but fails in Android's default browser.
The code is:
<style>
body {
background-color: gray;
}
</style>
<canvas id="mycanvas" width="64" height="64"></canvas>
<script>
var image = new Image();
image.src = 'image.png';
image.onload = function () { //once the image finishes loading
var context = document.getElementById("mycanvas").getContext("2d");
context.drawImage(image, 0, 0);
var imageData = context.getImageData(0, 0, 64, 64);
var pixels = imageData.data;
var numPixels = pixels.length;
for (var i = 0; i < numPixels; i++) { //for every pixel in the image
var index = i * 4;
var average = (pixels[index] + pixels[index + 1] + pixels[index + 2]) / 3;
pixels[index] = average + 255; //red is increased
pixels[index + 1] = average; //green
pixels[index + 2] = average; //blue
//pixels[index + 3] = pixels[index + 3]; //no changes to alpha
}
context.clearRect(0, 0, 64, 64); //clear the image
context.putImageData(imageData, 0, 0); //places the modified image instead
}
</script>
The summary is:
set the background color to gray so alpha can be observed easier
create a canvas 64 by 64
load a image of a smiley face on a transparent background
draw the image onto the canvas
get the image's data
for every pixel, make the red stronger
replace the altered image on the canvas
The smiley face looks like this (block-quoted so you can tell it's transparent):
However, in comparison with the chrome and android browser,
The background of the android drawing is reddish while the chrome drawing is completely transparent.
So...
What happened here?
How can I change the code so that the android drawing matches with the chrome drawing?
Note: I already tried if (pixels[index + 3] == 0) continue;, and I'm aware of this, but it won't work for images with varying opacity.
Ok, I have a result.
First of all look at your loop:
for (var i = 0; i < numPixels; i++) { //for every pixel in the image
var index = i * 4;
index will be more than 3 times bigger than numPixels. And will get undefined values. And average will be NaN. But, then I fixed this - result was the same.
So I tried to use fillStyle and fillRect for every pixel. All becomes fine. My code:
function putImageData(ctx, imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight) {
var data = imageData.data;
var height = imageData.height;
var width = imageData.width;
dirtyX = dirtyX || 0;
dirtyY = dirtyY || 0;
dirtyWidth = dirtyWidth !== undefined ? dirtyWidth : width;
dirtyHeight = dirtyHeight !== undefined ? dirtyHeight : height;
var limitBottom = dirtyY + dirtyHeight;
var limitRight = dirtyX + dirtyWidth;
for (var y = dirtyY; y < limitBottom; y++) {
for (var x = dirtyX; x < limitRight; x++) {
var pos = y * width + x;
//adding red increased here
ctx.fillStyle = 'rgba(' + data[pos * 4 + 0] + 255 + ',' + data[pos * 4 + 1] + ',' + data[pos * 4 + 2] + ',' + (data[pos * 4 + 3] / 255) + ')';
ctx.fillRect(x + dx, y + dy, 1, 1);
}
}
};
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gcVBAYmslkm5QAAAB1pVFh0Q29tbWVudAAAAAAAQ3JlYXRlZCB3aXRoIEdJTVBkLmUHAAABc0lEQVR42u2a3QrDMAiFZ9j7v7K7CpTRVtt4NCEnsJt1BP1y4l8nqvrZebXP5osACIAACIAACIAACIAACIAACIAAqpaIlPXkgpwHiIiqqtw5efa8f7csgIgTVVU5AlwGAELOSAjfLKndOWFBQyohVAHWPR/dCwEBCiDCYDSIViH5p/v87xUZZ8IUkJHGEGpoyLu/QjZomffeE+37xwthFH5aKdwNtQyOyhjT1QGzXosWaYBljMdY72laPUZZDLBq+6jTPO41xRXwGB/1Gw5ECOC6StxSASMQ2o5OQ9Jg5VxviYFI5KxgSQBXzmYNPlLaYctw72jr7ncd2DQx4KkCKud/cACeQNghvAmaCDjhCvBCOFODJX2Pgkp7gben+vR5pAqgL0aip8KI2ABNgyMRGzFiT1FARI+eWTDB3w7P6nhKHVBd5pYDGFVABsCU/wccHblLaxUNEwzACvKHB8EVFoeiBEAABEAABEAABEAABEAAe64fre4tZAeLAbcAAAAASUVORK5CYII=';
image.onload = function () {
var context = document.getElementById("mycanvas").getContext("2d"),
imageData;
context.drawImage(image, 0, 0);
imageData = context.getImageData(0, 0, 64, 64);
putImageData(context, imageData, 0, 0);
}

Animating canvas to look like tv noise

I have a function named generateNoise() which creates a canvas element and paints random RGBA values to it; which, gives the appearance of noise.
My Question
What would be the best way to infinitely animate the noise to give the appearance of movement. So that it may have more life?
JSFiddle
function generateNoise(opacity) {
if(!!!document.createElement('canvas').getContext) {
return false;
}
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
x,y,
r,g,b,
opacity = opacity || .2;
canvas.width = 55;
canvas.height = 55;
for (x = 0; x < canvas.width; x++){
for (y = 0; y < canvas.height; y++){
r = Math.floor(Math.random() * 255);
g = Math.floor(Math.random() * 255);
b = Math.floor(Math.random() * 255);
ctx.fillStyle = 'rgba(' + r + ',' + b + ',' + g + ',' + opacity + ')';
ctx.fillRect(x,y,1,1);
}
}
document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
}
generateNoise(.8);
Update 1/2017: I rewrote the entire answer as it started to become rather messy, and to address some of the issues pointed out in the comments. The original answer can be found here. The new answer has in essence the same code but improved, and with a couple of new techniques, one utilizes a new feature available since this answer was first posted.
For a "true" random look we would need to use pixel-level rendering. We can optimize this using 32-bit unsigned buffers instead of 8-bit, and we can also turn off the alpha-channel in more recent browsers which speeds up the entire process (for older browsers we can simply set a black opaque background for the canvas element).
We create a reusable ImageData object once outside the main loop so the main cost is only putImageData() and not both inside the loop.
var ctx = c.getContext("2d", {alpha: false}); // context without alpha channel.
var idata = ctx.createImageData(c.width, c.height); // create image data
var buffer32 = new Uint32Array(idata.data.buffer); // get 32-bit view
(function loop() {
noise(ctx);
requestAnimationFrame(loop)
})()
function noise(ctx) {
var len = buffer32.length - 1;
while(len--) buffer32[len] = Math.random() < 0.5 ? 0 : -1>>0;
ctx.putImageData(idata, 0, 0);
}
/* for browsers wo/2d alpha disable support */
#c {background:#000}
<canvas id=c width=640 height=320></canvas>
A very efficient way, at the cost of some memory but reduced cost on the CPU, is to pre-render a larger off-screen canvas with the noise once, then place that canvas into the main one using random integer offsets.
It require a few extra preparation steps but the loop can run entirely on the GPU.
var w = c.width;
var h = c.height;
var ocanvas = document.createElement("canvas"); // create off-screen canvas
ocanvas.width = w<<1; // set offscreen canvas x2 size
ocanvas.height = h<<1;
var octx = ocanvas.getContext("2d", {alpha: false});
var idata = octx.createImageData(ocanvas.width, ocanvas.height);
var buffer32 = new Uint32Array(idata.data.buffer); // get 32-bit view
// render noise once, to the offscreen-canvas
noise(octx);
// main loop draw the offscreen canvas to random offsets
var ctx = c.getContext("2d", {alpha: false});
(function loop() {
var x = (w * Math.random())|0; // force integer values for position
var y = (h * Math.random())|0;
ctx.drawImage(ocanvas, -x, -y); // draw static noise (pun intended)
requestAnimationFrame(loop)
})()
function noise(ctx) {
var len = buffer32.length - 1;
while(len--) buffer32[len] = Math.random() < 0.5 ? 0 : -1>>0;
ctx.putImageData(idata, 0, 0);
}
/* for browsers wo/2d alpha disable support */
#c {background:#000}
<canvas id=c width=640 height=320></canvas>
Do note though that with the latter technique you may risk getting "freezes" where the new random offset is similar to the previous one. To work around this problem, set criteria for the random position to disallow too close positions in a row.
I tried to make a similar function a while ago. I set each pixel random value, and in addition to that, I overlayed a sinusodial wave that traveled upwards with time just to make it look more realistic. You can play with the constants in the wave to get different effects.
var canvas = null;
var context = null;
var time = 0;
var intervalId = 0;
var makeNoise = function() {
var imgd = context.createImageData(canvas.width, canvas.height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
var c = 7 + Math.sin(i/50000 + time/7); // A sine wave of the form sin(ax + bt)
pix[i] = pix[i+1] = pix[i+2] = 40 * Math.random() * c; // Set a random gray
pix[i+3] = 255; // 100% opaque
}
context.putImageData(imgd, 0, 0);
time = (time + 1) % canvas.height;
}
var setup = function() {
canvas = document.getElementById("tv");
context = canvas.getContext("2d");
}
setup();
intervalId = setInterval(makeNoise, 50);
<canvas id="tv" width="400" height="300"></canvas>
I used it as a preloader on a site. I also added a volume rocker as a loading bar, here's a screenshot:
I re-wrote your code so each step is separate so you can re-use things without having to create and re-create each time, reduced in-loop calls and hopefully made it clear enough to be able to follow by reading it.
function generateNoise(opacity, h, w) {
function makeCanvas(h, w) {
var canvas = document.createElement('canvas');
canvas.height = h;
canvas.width = w;
return canvas;
}
function randomise(data, opacity) { // see prev. revision for 8-bit
var i, x;
for (i = 0; i < data.length; ++i) {
x = Math.floor(Math.random() * 0xffffff); // random RGB
data[i] = x | opacity; // set all of RGBA for pixel in one go
}
}
function initialise(opacity, h, w) {
var canvas = makeCanvas(h, w),
context = canvas.getContext('2d'),
image = context.createImageData(h, w),
data = new Uint32Array(image.data.buffer);
opacity = Math.floor(opacity * 0x255) << 24; // make bitwise OR-able
return function () {
randomise(data, opacity); // could be in-place for less overhead
context.putImageData(image, 0, 0);
// you may want to consider other ways of setting the canvas
// as the background so you can take this out of the loop, too
document.body.style.backgroundImage = "url(" + canvas.toDataURL("image/png") + ")";
};
}
return initialise(opacity || 0.2, h || 55, w || 55);
}
Now you can create some interval or timeout loop which keeps re-invoking the generated function.
window.setInterval(
generateNoise(.8, 200, 200),
100
);
Or with requestAnimationFrame as in Ken's answer
var noise = generateNoise(.8, 200, 200);
(function loop() {
noise();
requestAnimationFrame(loop);
})();
DEMO
Ken's answer looked pretty good, but after looking at some videos of real TV static, I had some ideas and here's what I came up with (two versions):
http://jsfiddle.net/2bzqs/
http://jsfiddle.net/EnQKm/
Summary of changes:
Instead of every pixel being independently assigned a color, a run of multiple pixels will get a single color, so you get these short, variable-sized horizontal lines.
I apply a gamma curve (with the Math.pow) to bias the color toward black a little.
I don't apply the gamma in a "band" area to simulate the banding.
Here's the main part of the code:
var w = ctx.canvas.width,
h = ctx.canvas.height,
idata = ctx.createImageData(w, h),
buffer32 = new Uint32Array(idata.data.buffer),
len = buffer32.length,
run = 0,
color = 0,
m = Math.random() * 6 + 4,
band = Math.random() * 256 * 256,
p = 0,
i = 0;
for (; i < len;) {
if (run < 0) {
run = m * Math.random();
p = Math.pow(Math.random(), 0.4);
if (i > band && i < band + 48 * 256) {
p = Math.random();
}
color = (255 * p) << 24;
}
run -= 1;
buffer32[i++] = color;
}
I happen to have just written a script that does just this, by getting the pixels from a black canvas and just altering random alpha values and using putImageData
Result can be found at http://mouseroot.github.io/Video/index.html
var currentAnimationFunction = staticScreen
var screenObject = document.getElementById("screen").getContext("2d");
var pixels = screenObject.getImageData(0,0,500,500);
function staticScreen()
{
requestAnimationFrame(currentAnimationFunction);
//Generate static
for(var i=0;i < pixels.data.length;i+=4)
{
pixels.data[i] = 255;
pixels.data[i + 1] = 255;
pixels.data[i + 2] = 255;
pixels.data[i + 3] = Math.floor((254-155)*Math.random()) + 156;
}
screenObject.putImageData(pixels,0,0,0,0,500,500);
//Draw 'No video input'
screenObject.fillStyle = "black";
screenObject.font = "30pt consolas";
screenObject.fillText("No video input",100,250,500);
}
Mine doesn't look identical to real TV static, but it's similar nonetheless. I'm just looping through all the pixels on canvas, and changing the RGB colour components of each pixel at a random coordinate to a random colour. The demo can be found over at CodePen.
The code is as follows:
// Setting up the canvas - size, setting a background, and getting the image data(all of the pixels) of the canvas.
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
canvasData = ctx.createImageData(canvas.width, canvas.height);
//Event listeners that set the canvas size to that of the window when the page loads, and each time the user resizes the window
window.addEventListener("load", windowResize);
window.addEventListener("resize", windowResize);
function windowResize(){
canvas.style.width = window.innerWidth + 'px';
canvas.style.height = window.innerHeight + 'px';
}
//A function that manipulates the array of pixel colour data created above using createImageData()
function setPixel(x, y, r, g, b, a){
var index = (x + y * canvasData.width) * 4;
canvasData.data[index] = r;
canvasData.data[index + 1] = g;
canvasData.data[index + 2] = b;
canvasData.data[index + 3] = a;
}
window.requestAnimationFrame(mainLoop);
function mainLoop(){
// Looping through all the colour data and changing each pixel to a random colour at a random coordinate, using the setPixel function defined earlier
for(i = 0; i < canvasData.data.length / 4; i++){
var red = Math.floor(Math.random()*256);
var green = Math.floor(Math.random()*256);
var blue = Math.floor(Math.random()*256);
var randX = Math.floor(Math.random()*canvas.width);
var randY = Math.floor(Math.random()*canvas.height);
setPixel(randX, randY, red, green, blue, 255);
}
//Place the image data we created and manipulated onto the canvas
ctx.putImageData(canvasData, 0, 0);
//And then do it all again...
window.requestAnimationFrame(mainLoop);
}
You can do it like this:
window.setInterval('generateNoise(.8)',50);
The 2nd arg 50 is a delay in milliseconds. Increasing 50 will slow it down and decreasing visa versa.
though.. this is going to severely affect web page performance. If it were me, I'd do the rendering server-side and render a handful of frame iterations and output as an animated gif. Not quite the same as infinite randomness, but would be a huge performance boost and IMO most people won't even notice.

Updating image data using putImageData on a resized canvas element

I have a static image (a png) that I'm drawing on a canvas element using drawImage.
var _canvas = null;
var _context = null;
var _curImageData;
function copyImageToCanvas(aImg)
{
_canvas = document.getElementById("canvas");
var w = aImg.naturalWidth;
var h = aImg.naturalHeight;
_canvas.width = w;
_canvas.height = h;
_context = _canvas.getContext("2d");
_context.clearRect(0, 0, w, h);
_context.drawImage(aImg, 0, 0);
_curImageData = _context.getImageData(0, 0, w, h);
}
I then manipulate the image data pixel by pixel (setting the opacity to 255 or 0 depending on the pixel value) and then update the canvas using putImageData.
function updateImage(maxPixelValToShow)
{
for (var x = 0; x < _curImageData.width; x++)
for (var y = 0; y < _curImageData.height; y++)
{
var offset = (y * _curImageData.width + x) * 4;
var r = _curImageData.data[offset];
var g = _curImageData.data[offset + 1];
var b = _curImageData.data[offset + 2];
var a = _curImageData.data[offset + 3];
var pixelNum = ((g * 255) + b);
//if greater than max or black/no data
if (pixelNum > maxPixelValToShow || (!r && !g && !b)) {
_curImageData.data[offset + 3] = 0;
} else {
_curImageData.data[offset + 3] = 255;
}
}
_context.putImageData(_curImageData, 0, 0);
}
And this all works perfectly. The issue I'm having is when I create a canvas twice the size of my image (or half the size, for that matter) and draw the image to fit the canvas size.
function copyImageToCanvas(aImg)
{
_canvas = document.getElementById("canvas");
var w = aImg.naturalWidth * 2; //double the size!
var h = aImg.naturalHeight * 2; //double the size!
_canvas.width = w;
_canvas.height = h;
_context = _canvas.getContext("2d");
_context.clearRect(0, 0, w, h);
_context.drawImage(aImg, 0, 0, w, h);
_curImageData = _context.getImageData(0, 0, w, h);
}
I'm getting lots of strange artifacts around the edges of my image when I call my updateImage function. Does anyone know a) why this is happening and b) what can I do about it?
Here are some images to show what is being generated:
The original image
The original image after my updateImage function call
The resized image
The resized image after my updateImage function call
[Solution]
Thanks Adam and sunetos, that was the problem. It worked fine once I setup one canvas to store the original file data and do the pixel manipulation and another only for display. Code snippet below:
function updateImage(maxPixelValToShow) {
//manipulate the _workingContext data
_workingContext.putImageData(_curImageData, 0, 0);
_displayContext.clearRect(0, 0, _workingCanvas.width*_scale, _workingCanvas.height*_scale);
_displayContext.drawImage(_workingCanvas, 0, 0, _workingCanvas.width*_scale, _workingCanvas.height*_scale);
}
It looks like the image smoothing used by the browser when scaling up the image in drawImage() antialiased the edges of your shape, causing new intermediate color values around the edge that are not handled by your updateImage() function. Like Adam commented, you should apply your updateImage() logic against the unmodified original pixels, and then scale it.

Categories