Creating image from Array in javascript and Html5 - javascript

Here is my code. I created imageData 2D array in javascript. After I put all pixels into the this array, I want to create image and put these values into the image.
var imageData = new Array(width);
var image = new Image;
for (var i = 0; i < width; i++) {
imageData[i] = new Array(height);
}
image.src = imageData; //Here is the problem. I want to do that.

To create an image from array you can do this:
var width = 400,
height = 400,
buffer = new Uint8ClampedArray(width * height * 4); // have enough bytes
The * 4 at the end represent RGBA which we need to be compatible with canvas.
Fill the buffer with some data, for example:
for(var y = 0; y < height; y++) {
for(var x = 0; x < width; x++) {
var pos = (y * width + x) * 4; // position in buffer based on x and y
buffer[pos ] = ...; // some R value [0, 255]
buffer[pos+1] = ...; // some G value
buffer[pos+2] = ...; // some B value
buffer[pos+3] = 255; // set alpha channel
}
}
When filled use the buffer as source for canvas:
// create off-screen canvas element
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = width;
canvas.height = height;
// create imageData object
var idata = ctx.createImageData(width, height);
// set our buffer as source
idata.data.set(buffer);
// update canvas with new data
ctx.putImageData(idata, 0, 0);
Note that you could use the imageData buffer (here: idata.data) instead of creating your own. Creating your own is really only useful if you use for example floating point values or get the buffer from some other source - setting the buffer as above will take care of clipping and rounding the values for you though.
Now the data in your custom array is copied to the canvas buffer. Next step is to create an image file:
var dataUri = canvas.toDataURL(); // produces a PNG file
Now you can use the data-uri as source for an image:
image.onload = imageLoaded; // optional callback function
image.src = dataUri

You can't make an image.src like that.
A valid dataURL is a base64 encoded string with a type prefix--not an array.
The image data array associated with a canvas is an Uint8ClampedArray--not a normal javascript array.
Here's one way to create a pixel array that you can manipulate:
A Demo: http://jsfiddle.net/m1erickson/956kC/
// create an offscreen canvas
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
// size the canvas to your desired image
canvas.width=40;
canvas.height=30;
// get the imageData and pixel array from the canvas
var imgData=ctx.getImageData(0,0,40,30);
var data=imgData.data;
// manipulate some pixel elements
for(var i=0;i<data.length;i+=4){
data[i]=255; // set every red pixel element to 255
data[i+3]=255; // make this pixel opaque
}
// put the modified pixels back on the canvas
ctx.putImageData(imgData,0,0);
// create a new img object
var image=new Image();
// set the img.src to the canvas data url
image.src=canvas.toDataURL();
// append the new img object to the page
document.body.appendChild(image);

Create a canvas element of the right size and get its 2D rendering context. You don't have to add this canvas to the document. Use the context to create an ImageData object. Copy the values from your array into the ImageData object. In your case, it might be more efficient to populate the ImageData object in the first place, instead of a separate array. Use the context's putImageData to draw the pixel data. Then, depending on the specific requirements of "Creating image," you might need to serialize the canvas into a data uri, so that you can fill in an img element's src.

Related

Trying to draw image from pixel array on canvas

I have a pixel-array of 256 values that looks something like this:
[-7.440151952041672e-45, -3.549412689007182e-44, -1.6725845544560632e-43, -7.785321621854041e-43, -3.579496378208359e-42, -1.6256392941914181e-41, ...]
What I am trying to achieve is, to draw this pixel array image onto the canvas. The reason why I need this, is because I will need recalculate the pixel array based on a convolution value to redraw the image with a specific filter over it.
I am currently trying to draw it using this:
function generate_image() {
// create an offscreen canvas
var canvas = document.createElement('canvas');
canvas.setAttribute("id", "canvas_id");
canvas.style.cssText = 'width: 400px; height: 400px; z-index: 1;';
document.body.appendChild(canvas);
var ctx=canvas.getContext("2d");
var images = generate_image_array_data();
// This is the pixel array of the image
var image = images[2];
var palette = ctx.getImageData(0, 0, 160, 120);
palette.data.set(new Uint8ClampedArray(image));
ctx.putImageData(palette, 0, 0);
}
Using the above code nothing happens on the canvas. I am fairly certain I am doing something wrong, but I am not exactly sure what. If anyone would be able to point me in the right direction, that would be greatly appreciated.
The log you shown can not be the one of an Uint8ClampedArray.
Clamped Uint8 values can't be negative, nor floats.
These are thus either 32 bits float values, or 64 bits float ones.
Once you determine which it is, you can convert it to clamped Uint8 values by doing
const data = new Uint8ClampedArray( original_data.buffer );
if original_data is already a TypedArray.
In case it is not, but rather a normal Array, you'd have to first rebuild a TypedArray from the values in that Array and then do the same conversion.
Assuming 64 bits float values:
const data = new Uint8ClampedArray( new Float64Array( images[ 2 ] ).buffer );
const palette = new ImageData( data, 160, 120 );
generate_image();
function generate_image() {
// create an offscreen canvas
var canvas = document.createElement('canvas');
canvas.setAttribute("id", "canvas_id");
canvas.style.cssText = 'width: 400px; height: 400px; z-index: 1;';
document.body.appendChild(canvas);
var ctx=canvas.getContext("2d");
var images = generate_image_array_data();
// This is the pixel array of the image
var image = images[2];
var data = new Uint8ClampedArray( new Float64Array( image ).buffer );
var palette = new ImageData(data, 3,4);
ctx.putImageData(palette, 0, 0);
ctx.imageSmootingEnabled = false;
ctx.globalCompositeOperation = "copy";
ctx.drawImage(canvas, 0, 0, 3, 4, 0, 0, canvas.width, canvas.height);
}
function generate_image_array_data() {
return [, , [-7.440151952041672e-45, -3.549412689007182e-44, -1.6725845544560632e-43, -7.785321621854041e-43, -3.579496378208359e-42, -1.6256392941914181e-41 ] ];
}
PS: Don't call getImageData if you don't need the pixels on the canvas, prefer ctx.createImageData(width, height) or even new ImageData(width, height), which will both avoid your canvas bitmap buffer be (slowly) moved from the GPU to the CPU for nothing

How to copy canvas image data to some other variable?

I am working on a small app, that loads user image onto a server, lets him choose one of the filters and gives image back.
I need to somehow save the initial image data with no filters applied.
But as i found out, in JS there is no natural way to copy vars.
I tried using LoDash _.clone() and one of the jQuery functions to do this, but they didn't work.
When I applied a cloned data to image, function putImageData couldn't get the cloned data because of the wrong type.
It seems, that clone functions somehow ignore object types.
Code:
var img = document.getElementById("image");
var canvas = document.getElementById("imageCanvas");
var downloadLink = document.getElementById("download");
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0, img.width, img.height);
document.getElementById("image").remove();
initialImageData = context.getImageData(0, 0, canvas.width, canvas.height); //initialImageData stores a reference to data, but I need a copy
///////////////////////
normalBtn.onclick = function(){
if(!(currentState == converterStates.normal)){
currentState = converterStates.normal;
//here I need to apply cloned normal data
}
};
So, what can I do here???
Thanks!!!
The correct way to copy a typed array is via the static function from
eg
var imageData = ctx.getImageData(0,0,100,100);
var copyOfData = Uint8ClampedArray.from(imageData.data); // create a Uint8ClampedArray copy of imageData.data
It will also allow you to convert the type
var copyAs16Bit = Uint16Array.from(imageData.data); // Adds high byte. 0xff becomes 0x00ff
Note that when converting to a smaller type the extra bits are truncated for integers. When converting from floats the value not the bits are copied. When copying between signed and unsigned ints the bits are copied eg Uint8Array to Int8Array will convert 255 to -1. When converting from small int to larger uint eg Int8Array to Uint32Array will add on bits -1 becomes 0xffff
You can also add optional map function
// make a copy with aplha set to half.
var copyTrans = Uint8ClampedArray.from(imageData.data, (d, i) => i % 4 === 3 ? d >> 1 : d);
typedArray.from will create a copy of any array like or iterable objects.
Use :
var image = …;
var data = JSON.parse(JSON.stringify(image).data);
var arr = new Uint8ClampedArray(data);
var copy = new ImageData(arr, image.width, image.height);
An ImageData object holds an Uint8ClampedArray which itself holds an ArrayBuffer.
To clone this ArrayBuffer, you can use its slice method, or the one from the TypedArray View you get :
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'orange';
ctx.fillRect(0,0,300,150);
var original = ctx.getImageData(0,0,300,150);
var copiedData = original.data.slice();
var copied = new ImageData(copiedData, original.width, original.height);
// now both hold the same values
console.log(original.data[25], copied.data[25]);
// but can be modified independently
copied.data[25] = 0;
console.log(original.data[25], copied.data[25]);
<canvas id="canvas"></canvas>
But in your case, an easier solution, is to call twice ctx.getImageData.
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'orange';
ctx.fillRect(0,0,300,150);
var original = ctx.getImageData(0,0,300,150);
var copied = ctx.getImageData(0,0,300,150);
// both hold the same values
console.log(original.data[25], copied.data[25]);
// and can be modified independently
copied.data[25] = 0;
console.log(original.data[25], copied.data[25]);
<canvas id="canvas"></canvas>
And an complete example :
var ctx = canvas.getContext('2d');
var img = new Image();
// keep these variables globally accessible to our script
var initialImageData, filterImageData;
var current = 0; // just to be able to switch easily
img.onload = function(){
// prepare our initial state
canvas.width = img.width/2;
canvas.height = img.height/2;
ctx.drawImage(img, 0,0, canvas.width, canvas.height);
// this is the state we want to save
initialImageData = ctx.getImageData(0,0,canvas.width,canvas.height);
// get an other, independent, copy of the current state
filterImageData = ctx.getImageData(0,0,canvas.width,canvas.height);
// now we can modify one of these copies
applyFilter(filterImageData);
button.onclick = switchImageData;
switchImageData();
}
// remove red channel
function applyFilter(image){
var d = image.data;
for(var i = 0; i < d.byteLength; i+=4){
d[i] = 0;
}
}
function switchImageData(){
// use either the original one or the filtered one
var currentImageData = (current = +!current) ?
filterImageData : initialImageData;
ctx.putImageData(currentImageData, 0, 0);
log.textContent = current ? 'filtered' : 'original';
}
img.crossOrigin = 'anonymous';
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
<button id="button">switch imageData</button>
<code id="log"></code><br>
<canvas id="canvas"></canvas>
The same with slice:
var ctx = canvas.getContext('2d');
var img = new Image();
// keep these variables globally accessible to our script
var initialImageData, filterImageData;
var current = 0; // just to be able to switch easily
img.onload = function(){
// prepare our initial state
canvas.width = img.width/2;
canvas.height = img.height/2;
ctx.drawImage(img, 0,0, canvas.width, canvas.height);
// this is the state we want to save
initialImageData = ctx.getImageData(0,0,canvas.width,canvas.height);
// get an other, independent, copy of the current state
filterImageData = new ImageData(initialImageData.data.slice(), initialImageData.width, initialImageData.height);
// now we can modify one of these copies
applyFilter(filterImageData);
button.onclick = switchImageData;
switchImageData();
}
// remove red channel
function applyFilter(image){
var d = image.data;
for(var i = 0; i < d.byteLength; i+=4){
d[i] = 0;
}
}
function switchImageData(){
// use either the original one or the filtered one
var currentImageData = (current = +!current) ?
filterImageData : initialImageData;
ctx.putImageData(currentImageData, 0, 0);
log.textContent = current ? 'filtered' : 'original';
}
img.crossOrigin = 'anonymous';
img.src = 'https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg';
<button id="button">switch imageData</button>
<code id="log"></code><br>
<canvas id="canvas"></canvas>

Javascript Canvas: How to get the specific points on transparent png file?

Okay, I am confused with get Image Data function for
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData
I have a path image that is in png format with transparent background above. What I need to get are the coordinates x,y for both left and right edges of the path at height/2. (The points of the red arrows)
Is getImageData the right function to use? Can anyone give some advice on how to get them?
Thanks in advance.
Yes, use getImageData(x, y, width, height);
In the case you have only two colors (here transparent & white) :
var img = new Image();
img.onload = getPoints;
img.crossOrigin = 'anonymous';
img.src = "https://dl.dropboxusercontent.com/s/lvgvekzkyqkypos/path.png";
function getPoints(){
// set our canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = this.width;
canvas.height = this.height;
// draw the image
ctx.drawImage(this,0,0);
// get the middle y line
var imageData = ctx.getImageData(0,Math.floor(this.height/2), this.width, 1);
var data = imageData.data;
// set an empty object that will store our points
var pts = {x1: null, y1: Math.floor(this.height/2), x2: null, y2:Math.floor(this.height/2)};
// define the first opacity value
var color = 0;
// iterate through the dataArray
for(var i=0; i<data.length; i+=4){
// since we'relooking only for non-transparent pixels, we can check only for the 4th value of each pixel
if(data[i+3]!==color){
// set our value to this new one
color = data[i+3];
if(!pts.x1)
pts.x1 = i/4;
else
pts.x2 = i/4;
}
}
snippet.log('start points : '+pts.x1+'|'+pts.y1);
snippet.log('end points : '+pts.x2+'|'+pts.y2);
ctx.fillStyle = 'red';
ctx.fillRect(pts.x1-5, pts.y1, 10, 10);
ctx.fillRect(pts.x2-5, pts.y2, 10, 10);
document.body.appendChild(canvas);
}
body{background-color: blue}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Can't load images on canvas for my js game

I am making a mahjong game in js and I have a problem loading images on canvas
canvas
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 512;
//draw canvas
document.body.appendChild(canvas);
Arrays
//Array with Tiles & set length to 144 which are the requested tiles
var tiles = new Array(2);//will be 144
//2D map array for showing the images coordinates
var map = [[69,50],[100,150]];//will be 144 coordinates
my function update()
function update(){
for(var i=0;i<tiles.length;i++){
//make the tile object
tiles[i] = new Object();
tiles[i].id = i ;
tiles[i].selected = false;
//set the coordinates from map Array
tiles[i].x=map[i][0];
tiles[i].y=map[i][1];
//tiles[i].ready=false;
//These are for the image location works fine
//convert i to String
var sourceNumber = i.toString();
//add .png to String
var source = sourceNumber.concat(png);
//add /image
var source = dest.concat(source);
tiles[i].img = new Image();
tiles[i].img.onload = function(){
//tiles[i].ready=true;
ctx.drawImage(tiles[i].img,tiles[i].x,tiles[i].y,xdimension,ydimension);
};
tiles[i].img.src = source ;
}
}
I runned it on each of my browser it won't load images , I debugged on chrome and it says on ctx.drawImage(...); -> Uncaught TypeError: Cannot read property 'img' of undefined(repeated many times), So I tried the tiles[I].ready and after load images but still has that error.Any suggestions on how should I implement the loading of the tile images
The first time ctx.drawImage is called, the value for i is 2. The problem is that the for-loop (for(var i=0;i<tiles.length;i++)) has finished executing before any of the images have loaded. Consequently, the value of i at the time the onload function is called is the value at which the loop ceased being run. The easiest way around this is to save the index (i) into the img element itself, so that you can retrieve it in the onload handler.
Here's a simple adaption of your code that seems to work just fine.
The important changes are:
tiles[i].img.iVal = i;
and the body of the onload handler.
I also:
(a) added an array to hold hard-coded image names for convenience, rather than dynamically creating them (I'd have had to name some images into the format that the code computes)
(b) removed the xdimension and ydimension vars from the drawImage call since I dont know what they are.
(c) changed .concat(png) to .concat(".png") since it was easier than declaring a variable called png that holds the string .png
Anyway, here's the sample-code I used:
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('load', onDocLoaded, false);
var canvas, ctx, tiles, map;
function onDocLoaded()
{
canvas = newEl('canvas');
ctx = canvas.getContext('2d');
canvas.width = canvas.height = 512;
document.body.appendChild(canvas);
tiles = new Array(2);
map = [[69,50],[100,150]];
update();
}
var imgFileNames = ["img/girl.png", "img/redbaron.png"];
function update()
{
for(var i=0;i<tiles.length;i++)
{
//make the tile object
tiles[i] = new Object();
tiles[i].id = i ;
tiles[i].selected = false;
//set the coordinates from map Array
tiles[i].x=map[i][0];
tiles[i].y=map[i][1];
//tiles[i].ready=false;
//These are for the image location works fine
//convert i to String
// var sourceNumber = i.toString();
//add .png to String
// var source = sourceNumber.concat(".png");
//add /image
// var source = dest.concat(source);
tiles[i].img = new Image();
tiles[i].img.iVal = i;
tiles[i].img.onload =
function()
{
var curI = this.iVal;
ctx.drawImage(tiles[curI].img,tiles[curI].x,tiles[curI].y);
// ctx.drawImage(this,tiles[curI].x,tiles[curI].y); //equiv to above line
};
tiles[i].img.src = imgFileNames[i];
}
}
</script>
<style>
canvas
{
border: solid 1px red;
}
</style>
</head>
<body>
</body>
</html>

JavaScript iteration

I want to use JavaScript to draw a series of images onto an HTML5 canvas. I have the following while loop, which I had hoped would draw all of the images to the canvas, however, it is currently only drawing the first one:
function drawLevelOneElements(){
/*First, clear the canvas */
context.clearRect(0, 0, myGameCanvas.width, myGameCanvas.height);
/*This line clears all of the elements that were previously drawn on the canvas. */
/*Then redraw the game elements */
drawGameElements();
/*Draw the elements needed for level 1 (26/04/2012) */
var fileName = 1;
var imagePositionX = 20;
var imagePositionY = 30;
while(fileName < 11){
/*Create an array of images here, move to next element of array on each iteration */
var numbers = new Array();
numbers[0] = "1.png"
numbers[1] = "2.png"
numbers[3] = "3.png"
numbers[4] = "4.png"
numbers[5] = "5.png"
image.src = fileName+".png";
image.src = numbers[0];
image.onload = function(){
context.drawImage(image, imagePositionX, imagePositionY, 50, 50);
}
fileName = fileName+1;
imageY = imageY+20;
console.dir(fileName); /* displays in the console- helpful for debugging */
}
To talk through what I had hoped this function would do:
Load each of the images into a different element of the array (so 1.png would be in numbers[0], 2.png in numbers[1], etc. )
It would then take the global variable 'image', and assign its source to the contents of numbers[0]
Then draw that image at the specified position on the canvas.
Then increment the value of the variable fileName by 1, giving it a value of '2'
Next it would increment the value of the Y co-ordinate where it will draw the image on the canvas by 20- moving the position of the image to be drawn down by 20 pixels
After that it would go back to the start of the loop and draw the next image (2.png) on the canvas in a position that is 20 pixels below the position of the first image that was drawn.
It should continue doing this while the value of the variable 'fileName' is less than 11, i.e. it should draw 10 images each new one below the last one that was drawn.
However, for some reason, my function only draws the first image. Could someone point out what I'm doing wrong, and how I could correct this?
Thanks very much.
Edited and commented some points of your code.
The most effective change was at imageY = imageY+20; that was edited to use imagePositionY variable.
function drawLevelOneElements() {
/*First, clear the canvas */
context.clearRect(0, 0, myGameCanvas.width, myGameCanvas.height);
/*This line clears all of the elements that were previously drawn on the canvas. */
/*Then redraw the game elements */
drawGameElements();
/*Draw the elements needed for level 1 (26/04/2012) */
var fileName = 1;
var imagePositionX = 20;
var imagePositionY = 30;
while(fileName < 11){
/*Create an array of images here, move to next element of array on each iteration */
var numbers = new Array();
/* what is not used is not necessary :)
numbers[0] = "1.png"
numbers[1] = "2.png"
numbers[3] = "3.png"
numbers[4] = "4.png"
numbers[5] = "5.png"*/
image.src = fileName+".png";
// image.src = numbers[0];
image.onload = function(){
context.drawImage(image, imagePositionX, imagePositionY, 50, 50);
}
fileName = fileName+1;
imagePositionY = imagePositionY+20; //before: imageY = imageY+20;
console.dir(fileName); /* displays in the console- helpful for debugging */
}
If you take the drawImg stuff and shove it in its own function you can clean this up a bit :) Now we've yanked the async stuff out of the loop, so the image variable doesn't get over-written each time you loop. You're also using a for loop now, which to me is clearer to understand.
function drawLevelOneElements() {
// your stuff
for (var i = 0; i > 5; i++) {
drawImg(ctx, i, x, y);
// update x or y and whatever else
}
}
// put all your image drawing stuff here
function drawImg(ctx, i, x, y) {
var img = new Image();
img.src = i + ".png";
img.onload = function(){
ctx.drawImage(img, x, y, 50, 50);
}
}

Categories