JavaScript put Image data on top of canvas - javascript

I have the following code which creates a rectangle as shown in the image below:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<p id='one'></p>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = 'black';
ctx.fillRect(20, 20, 40, 40)
var imgData = ctx.createImageData(100, 100);
var i;
for (i = 0; i < imgData.data.length; i += 16) {
imgData.data[i + 0] = 255;
imgData.data[i + 1] = 0;
imgData.data[i + 2] = 0;
imgData.data[i + 3] = 255;
}
// ctx.putImageData(imgData, 10, 10);
</script>
</body>
</html>
When I make sure that the image data is added by not commenting ctx.putImageData , I get only the image data like the picture shown below:
How do I make sure that the image is created on top of the black rectangle in the sense that in the white spaces between the red lines?
I want to be able to see the black rectangle. I tried changing the alpha channel but that did not do anything.
Thanks in advance :).

putImageData will replace the targeted pixels with the ones contained in your ImageData, whatever they are.
This means that if your ImageData contains transparent pixels, these transparent pixels will be there once you put the ImageData on your canvas.
There are several ways to accomplish what you want though.
The one requiring the less code change, is to make your pixel manipulation from the current state of your context. By calling getImageData instead of createImageData, you will have an ImageData which contains the currently drawn pixels in the area you selected.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = 'black';
ctx.fillRect(20, 20, 40, 40);
// get the current pixels at (x, y, width, height)
var imgData = ctx.getImageData(10, 10, 100, 100);
var i;
// and do the pixel manip over these pixels
for (i = 0; i < imgData.data.length; i += 16) {
imgData.data[i + 0] = 255;
imgData.data[i + 1] = 0;
imgData.data[i + 2] = 0;
imgData.data[i + 3] = 255;
}
ctx.putImageData(imgData, 10, 10);
<canvas id="myCanvas"></canvas>
The main caveat is that getImageData is slower and requires more memory than createImageData, so if you are gonna do it every frame in an animation, it may not be suitable.
An other solution in this case (animation), is to use a second off-screen canvas, on which you will draw once your ImageData, an then draw this off-screen canvas on the main one using drawImage.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = 'black';
var gridImage = generateGrid(100, 100);
var x = 0;
anim();
/*
Makes your pixel manip on an off-screen canvas
Returns the off-screen canvas
*/
function generateGrid(width, height){
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var off_ctx = canvas.getContext('2d');
var imgData = off_ctx.createImageData(width, height);
for (i = 0; i < imgData.data.length; i += 16) {
imgData.data[i + 0] = 255;
imgData.data[i + 1] = 0;
imgData.data[i + 2] = 0;
imgData.data[i + 3] = 255;
}
off_ctx.putImageData(imgData, 0,0);
return canvas;
}
function anim(){
ctx.clearRect(0,0,c.width, c.height);
x = (x + 1) % (c.width + 100);
ctx.fillRect(x, 20, 40, 40);
// and here you draw your generated canvas
ctx.drawImage(gridImage, x - 10, 0);
requestAnimationFrame(anim);
}
<canvas id="myCanvas"></canvas>
You could also refactor your code in order to make your normal drawings (here fillRect) after you did draw the ImageData, but behind current drawings, thanks to the globalCompositeOperation property of your context:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// do first your pixel manip
var imgData = ctx.createImageData(100, 100);
var i;
for (i = 0; i < imgData.data.length; i += 16) {
imgData.data[i + 0] = 255;
imgData.data[i + 1] = 0;
imgData.data[i + 2] = 0;
imgData.data[i + 3] = 255;
}
ctx.putImageData(imgData, 10, 10);
// change the gCO to draw behind current non-transparent pixels
ctx.globalCompositeOperation = 'destination-over';
// now make your normal drawings
ctx.fillStyle = 'black';
ctx.fillRect(20, 20, 40, 40);
// reset the gCO
ctx.globalCompositeOperation = 'source-over';
<canvas id="myCanvas"></canvas>
And finally, if you target only next-gen browsers, then you could make use of the ImageBitmap object, which will produce the same result as the off-screen canvas, in less lines of code:
(async () => {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = 'black';
var gridImage = await generateGrid(100, 100);
var x = 0;
anim();
/*
Makes your pixel manip on an empty ImageData
Returns an Promise resolving to an ImageBitmap
*/
function generateGrid(width, height) {
var imgData = ctx.createImageData(width, height);
for (i = 0; i < imgData.data.length; i += 16) {
imgData.data[i + 0] = 255;
imgData.data[i + 1] = 0;
imgData.data[i + 2] = 0;
imgData.data[i + 3] = 255;
}
return createImageBitmap(imgData);
}
function anim() {
ctx.clearRect(0, 0, c.width, c.height);
x = (x + 1) % (c.width + 100);
ctx.fillRect(x, 20, 40, 40);
// and here you draw your generated canvas
ctx.drawImage(gridImage, x - 10, 0);
requestAnimationFrame(anim);
}
})();
<canvas id="myCanvas"></canvas>

I couldn't make it work with you exact code but when I tried with 2 images overlapping I managed to make them overlap.
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
</canvas>
<p id = 'one'></p>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = ctx.createImageData(100, 100);
var i;
for (i = 0; i < img.data.length; i += 6) {
img.data[i+0] = 255;
img.data[i+1] = 0;
img.data[i+2] = 0;
img.data[i+3] = 255;
}
var img2 = ctx.createImageData(100, 100);
var i;
for (i = 0; i < img2.data.length; i += 20) {
img2.data[i+0] = 0;
img2.data[i+1] = 255;
img2.data[i+2] = 0;
img2.data[i+3] = 255;
}
var pixels = 4*100*100;
var imgData1 = img.data;
var imgData2 = img2.data;
while (pixels--){
imgData1[pixels] = imgData1[pixels] * 0.5 + imgData2[pixels] *0.5;
}
img.data = imgData1;
ctx.putImageData(img, 10, 0);
</script>

Related

Replace average color pixel with images

I need to create a mosaic by replacing the pixel of an image on input with images for each colors. The images will be provided by me for some of the most important colors. Obviously it shall be rounded up to the nearest color, because i can't use a picture for every rgb color.
I found this code that i think it could be a good start but i don't know how replace a tile with an image.
var TILE_WIDTH=10;
var TILE_HEIGHT=10;
document.getElementById("input").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
};
// first function call to create photomosaic
function photomosaic(image) {
// Dimensions of each tile
var tileWidth = TILE_WIDTH;
var tileHeight = TILE_HEIGHT;
//creating the canvas for photomosaic
var canvas = document.createElement('canvas');
var context = canvas.getContext("2d");
canvas.height = image.height;
canvas.width = image.width;
var imageData = context.getImageData(0, 0, image.width, image.height);
var pixels = imageData.data;
// Number of mosaic tiles
var numTileRows = image.width / tileWidth;
var numTileCols = image.height / tileHeight;
//canvas copy of image
var imageCanvas = document.createElement('canvas');
var imageCanvasContext = canvas.getContext('2d');
imageCanvas.height = image.height;
imageCanvas.width = image.width;
imageCanvasContext.drawImage(image, 0, 0);
//function for finding the average color
function averageColor(row, column) {
var blockSize = 1, // we can set how many pixels to skip
data, width, height,
i = -4,
length,
rgb = {
r: 0,
g: 0,
b: 0
},
count = 0;
try {
data = imageCanvasContext.getImageData(column * TILE_WIDTH, row * TILE_HEIGHT, TILE_HEIGHT, TILE_WIDTH);
} catch (e) {
alert('Not happening this time!');
return rgb;
}
length = data.data.length;
while ((i += blockSize * 4) < length) {
++count; //
rgb.r += data.data[i];
rgb.g += data.data[i + 1];
rgb.b += data.data[i + 2];
}
// ~~ used to floor values
rgb.r = ~~(rgb.r / count);
rgb.g = ~~(rgb.g / count);
rgb.b = ~~(rgb.b / count);
return rgb;
}
// Loop through each tile
for (var r = 0; r < numTileRows; r++) {
for (var c = 0; c < numTileCols; c++) {
// Set the pixel values for each tile
var rgb = averageColor(r, c)
var red = rgb.r;
var green = rgb.g;
var blue = rgb.b;
// Loop through each tile pixel
for (var tr = 0; tr < tileHeight; tr++) {
for (var tc = 0; tc < tileWidth; tc++) {
// Calculate the true position of the tile pixel
var trueRow = (r * tileHeight) + tr;
var trueCol = (c * tileWidth) + tc;
// Calculate the position of the current pixel in the array
var pos = (trueRow * (imageData.width * 4)) + (trueCol * 4);
// Assign the colour to each pixel
pixels[pos + 0] = red;
pixels[pos + 1] = green;
pixels[pos + 2] = blue;
pixels[pos + 3] = 255;
};
};
};
};
// Draw image data to the canvas
context.putImageData(imageData, 0, 0);
return canvas;
}
function create() {
var image = document.getElementById('image');
var canvas = photomosaic(image);
document.getElementById("output").appendChild(canvas);
};
#output, .container {
text-align: center;
}
.inputDiv {
margin: 20px 0px;
}
<div class="container">
<img id="image"/>
<div class="inputDiv">
<input id="input" type="file" accept="image/*">
<button onclick="create()">create</button>
</div>
<div id="output"></div>
</div>
code by gurinderiitr

JavaScript - Generate random pixels on HTML5 canvas

I want to create a random generated image (random colors), like this one. But, I want to do it in javascript, but for some reason I am getting black screen.
Here is my code:
var g=document . createElement( 'canvas').getContext('2d');
g.canvas.width=g.canvas.height = 800;
g.imgd = g.getImageData(0, 0, 800, 800);
g.data = g.imgd.data;
g.data.forEach((_, index) => (index & 3) < 3 && (g.data[index] = Math.random()));
g.putImageData(g.imgd, 0, 0);
document.body.appendChild(g.canvas);;;
And i am getting black screen, and on some websites it is white screen. So what is what not working in my script? My english is not very good, but can someone explain what is wrong, my code dont'esnt working.
I also tried different dimensions of canvas and I dont see any errors so what is wrong?
You are using Math.random() which generates floats from 0 to 1 without including 1. Since you're applying zeroes to the color components (the data from getImageData().data), you get the color black (rgb(0, 0, 0)).
Here's a more readable solution:
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 800;
var ctx = canvas.getContext('2d');
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
for (var i = 0; i < imgData.data.length; i += 4) {
imgData.data[i] = randomInt(0, 255); // red
imgData.data[i+1] = randomInt(0, 255); // green
imgData.data[i+2] = randomInt(0, 255); // blue
imgData.data[i+3] = 255; // alpha
}
ctx.putImageData(imgData, 0, 0);
document.body.appendChild(canvas);
Math.random() returns a floating point number, not within the full range of 0-255. You can alternatively use .fillStyle() and set the color to a random hex color.
function pixels(width = 100, height = 100, size = 1, canvas) {
var canvas = canvas || document.createElement("canvas");
var ctx = canvas.getContext("2d");
var total = [];
canvas.width = width;
canvas.height = height;
function random() {
return "XXXXXX".replace(/X/g, function() {
var seed = "a0b1c2d3e4f56789";
return seed.charAt(Math.floor(Math.random() * seed.length))
})
};
for (var x = 0; x <= width; x += size) {
total.push(x)
};
total.forEach(function(value, index) {
for (var i = 0; i <= height; i++) {
ctx.fillStyle = "#" + random();
ctx.fillRect(value, total[i], size, size);
}
});
document.body.appendChild(canvas);
return ctx;
};
var c = pixels(window.innerWidth - 20, window.innerHeight - 20);

How to rescale image to draw with canvas?

If you have an idea ,
Starting from the code of this post In javascript , how to reverse y axis of canvas?( with the Flip rendered content solution)
i would like to draw this last image (200*200) in a 100*100 canvas, rescaling it using ctx.drawImage(ctx.canvas,0,0,200,200,0,0,100,100) but it only crops it
regards
Scale the context by 0.5 before drawing.
ctx.scale(0.5,0.5)
var i,j;
const n = 200;
const size = n ** 2; // ** is to power of
//const canvas = document.querySelector('canvas'); // not needed canvas is
// already defined with
// id="canvas"
const ctx = canvas.getContext("2d");
const imgData = ctx.createImageData(n, n);
const Z = [];
for (j = 0; j < size; j ++) { Z[j] = j * 256 / size }
Z[n * n - 1] = 0;
i = 0;
for (j = 0; j < size; j++) {
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = Z[j];
imgData.data[i++] = 255;
}
ctx.putImageData(imgData, 0, 0);
ctx.scale(0.5,0.5);
// flip the canvas
ctx.transform(1, 0, 0, -1, 0, canvas.height)
ctx.globalCompositeOperation = "copy"; // if you have transparent pixels
ctx.drawImage(ctx.canvas,0,0);
ctx.globalCompositeOperation = "source-over"; // reset to default
<canvas id="canvas" width=200 height=200></canvas>

Labels inside canvas pie charts

I am making a pie chart with canvas but I am unable to put labels into the canvas. I tried so many things... Can you help me?
HTML
<canvas id="can" width="200" height="200" />
JS
var D1 = 15;
var D2 = 15;
var D3 = 45;
var D4 = 25;
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
var lastend = 0;
var data = [D1,D2,D3,D4]; // If you add more data values make sure you add more colors
var myTotal = 0; // Automatically calculated so don't touch
var myColor = ["#ECD078","#D95B43","#C02942","#542437"];
var labels = ["25%","25%","25%","25%"];
for (var e = 0; e < data.length; e++) {
myTotal += data[e];
ctx.font = 'bold 15pt Calibri';
ctx.fillText(labels[e],15,15);
}
for (var i = 0; i < data.length; i++) {
ctx.fillStyle = myColor[i];
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2);
// Arc Parameters: x, y, radius, startingAngle (radians), endingAngle (radians), antiClockwise (boolean)
ctx.arc(canvas.width / 2, canvas.height / 2, canvas.height / 2, lastend, lastend + (Math.PI * 2 * (data[i] / myTotal)), false);
ctx.lineTo(canvas.width / 2, canvas.height / 2);
ctx.fill();
lastend += Math.PI * 2 * (data[i] / myTotal);
}
My intention is to put the labels[] number in order, inside the pie chart.
If its not too late, you may try this:
https://jsfiddle.net/rradik/kuqdwuyd/
<canvas id="canvas" width="200" height="200" />
var canvas;
var ctx;
var lastend = 0;
var pieColor = ["#ECD078","#D95B43","#C02942","#542437","#53777A"];
var pieData = [10,30,20,60,40];
var pieTotal = 10 + 30 + 20 + 60 + 40; // done manually for demo
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var hwidth = ctx.canvas.width/2;
var hheight = ctx.canvas.height/2;
for (var i = 0; i < pieData.length; i++) {
ctx.fillStyle = pieColor[i];
ctx.beginPath();
ctx.moveTo(hwidth,hheight);
ctx.arc(hwidth,hheight,hheight,lastend,lastend+
(Math.PI*2*(pieData[i]/pieTotal)),false);
ctx.lineTo(hwidth,hheight);
ctx.fill();
//Labels on pie slices (fully transparent circle within outer pie circle, to get middle of pie slice)
//ctx.fillStyle = "rgba(255, 255, 255, 0.5)"; //uncomment for debugging
// ctx.beginPath();
// ctx.moveTo(hwidth,hheight);
// ctx.arc(hwidth,hheight,hheight/1.25,lastend,lastend+
// (Math.PI*(pieData[i]/pieTotal)),false); //uncomment for debugging
var radius = hheight/1.5; //use suitable radius
var endAngle = lastend + (Math.PI*(pieData[i]/pieTotal));
var setX = hwidth + Math.cos(endAngle) * radius;
var setY = hheight + Math.sin(endAngle) * radius;
ctx.fillStyle = "#ffffff";
ctx.font = '14px Calibri';
ctx.fillText(pieData[i],setX,setY);
// ctx.lineTo(hwidth,hheight);
//ctx.fill(); //uncomment for debugging
lastend += Math.PI*2*(pieData[i]/pieTotal);
}
May not be perfect and very efficient one, but does the job nevertheless
The problem was that all your text was overlapping.
I simply changed the order of execution. The text is now drawn after the pie chart. One more thing, I added an offset to the text, each time the loop runs I offset by 50.
Working Example
var offset = 50;
for (var e = 0; e < data.length; e++) {
ctx.font = 'bold 15pt Calibri';
ctx.fillText(labels[e],offset*e,180);
}

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);
}

Categories