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>
Related
Is there any method to replace/remove colors by color range in Javascript, Opencv or anything else that can be operated on website?
As the above image. Is that possible to replace all the white color(It can be white or near white colors) with transparent color? Any suggestion would be appreciated.
With imagemagick this can be done quickly.
convert input.jpg -fuzz 6% -transparent white output.png
The value of -fuzz 6% can be adjusted to match "near white" thresholds.
Note: The format of JPEG has changed to PNG; which, supports transparency.
You could create a canvas and draw that image onto it, that way you're able to get pixel colors and manipulate them. (And also save the result)
This might lead you somewhere to start with. If you require further help, just comment.
EDIT: Little sample of what this should work like:
//Sets up canvas containing the image:
var img = document.getElementById("image");
img.crossOrigin = "Anonymous";
img.src = "https://i.imgur.com/X1fKQsK.jpg";
loadedBefore = false;
img.onload = function(){
if(loadedBefore) return;
else loadedBefore = true;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.width,img.height);
//Finds pixels matching color black:
for(x=0; x<canvas.width; x++){
for(y=0; y<canvas.height; y++){
imgdata = ctx.getImageData(x,y,1,1);
color = imgdata.data; //Gets color of coordinate (with 1 pixel in size)
if(color[0] > 250 && color[1] > 250 && color[2] > 250){ //Checks if color is pretty white
color[3] = 0; //Sets alpha to 0 -> Makes color transparent
ctx.putImageData(imgdata,x,y);
}
}
}
img.src = canvas.toDataURL(); //Set image to display canvas content / update image
console.log("done!");
}
<img id="image"/>
You can apparently not just load an image from some other website and modifiy it in the canvas, unless you set img.crossOrigin = "Anonymous" and the other website allows it. I got no clue on what exactly happens there, I just know that it works with imgur.com. (That's why everything's in the onload function now)
The loadedBefore stuff is because StackOverflow apparently calls the img.onload function pretty often, you won't have this issue if you use your own image so you don't need the crossOrigin and onload stuff.....
Just a function to do the stuff:
function whiteToTransparent(img){
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0,img.width,img.height);
//Finds pixels matching color black:
for(x=0; x<canvas.width; x++){
for(y=0; y<canvas.height; y++){
imgdata = ctx.getImageData(x,y,1,1);
color = imgdata.data;
if(color[0] > 250 && color[1] > 250 && color[2] > 250){
color[3] = 0;
ctx.putImageData(imgdata,x,y);
}
}
}
img.src = canvas.toDataURL();
}
In general we can convert the HTML elements to string and then we can insert it into DOM later when needed. Similarly, I want to convert the "CANVAS" element to string along with its context properties.
In the following example, I am getting the string value of span tag with outerHTML property. Likewise I want to get the "CANVAS"element along with context properties.
Is there any method or property for this support?
Example code snippets:
var sp=document.createElement("span");
sp.innerHTML = "E2"
var e2 = sp.outerHTML;
$("#test1").append(e2);
var c=document.createElement("CANVAS");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.arcTo(150,20,150,70,50);
ctx.lineTo(150,120);
ctx.stroke();
var cn = c.outerHTML;
$("#test2").append(cn);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1">
<span>E1</span>
</div>
<div id="test2">
</div>
Seems like you already know how to get dom properties of the canvas object.
Now you only need "context" infos (image data as I understand it)
You can get the image data as a base64 string like this:
function CreateDrawing(canvasId) {
let canvas = document.getElementById(canvasId);
let ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.arcTo(150,20,150,70,50);
ctx.lineTo(150,120);
ctx.stroke();
}
function GetDrawingAsString(canvasId) {
let canvas = document.getElementById(canvasId);
let pngUrl = canvas.toDataURL(); // PNG is the default
// or as jpeg for eg
// var jpegUrl = canvas.toDataURL("image/jpeg");
return pngUrl;
}
function ReuseCanvasString(canvasId, url) {
let img = new Image();
img.onload = () => {
// Note: here img.naturalHeight & img.naturalWidth will be your original canvas size
let canvas = document.getElementById(canvasId);
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
}
img.src = url;
}
// Create something
CreateDrawing("mycanvas");
// save the image data somewhere
var url = GetDrawingAsString("mycanvas");
// re use it later
ReuseCanvasString("replicate", url);
<canvas id="mycanvas"></canvas>
<canvas id="replicate"></canvas>
In short no!
You should realize the difference between a standard DOM-element and a canvas-element:
A created DOM-element is part of the mark-up language that can be viewed and changed.
In the canvas a vector image is drawn based upon the rules created in script. These rules are not stored in the element as text but as the image and can't be subtracted from the canvas element.
However there are other possibilities. We can get the variables from the ctx-object. But no info about coordinates:
var c=document.createElement("CANVAS");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(100,20);
ctx.arcTo(150,20,150,70,50);
ctx.lineTo(150,120);
ctx.stroke();
var ctxInfo = [];
for (ctxKey in ctx)
{
if (Object.prototype.toString.call(ctx[ctxKey]) !== "[object Function]" )
{
ctxInfo.push(ctxKey + " : " + ctx[ctxKey]);
}
}
console.log(ctxInfo);
To transfer from one canvas to the other I would keep a list (array or object) of instructions and write a generic function that applies them.
canvasObject = [["beginPath"], ["moveTo", 20, 20], ["lineTo", 100, 20], ["arcTo", 150, 20, 150, 70, 50], ["lineTo", 150, 120], ["stroke"]];
function createCanvas(cnvsObj)
{
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
cnvsObj.forEach(function(element){
//loop through instructions
ctx[element[0]].apply(ctx, element.slice(1));
});
return c;
}
var a = createCanvas(canvasObject);
document.body.appendChild(a);
I have an imageCanvas with it's Transform matrix
Image = new image();
image.src = //stuff;
imageContext.drawImage(Image, 0, 0);
var t = imageContext.currentTransform;
that is drawn on another canvas
context.drawImage(imageCanvas, 0, 0);
on which I draw lines
context.moveTo(mousePos.X, mousePos.Y);
context.lineTo(currentPos.X, currentPos.Y);
context.stroke();
I save my lines into a vector of objects 'lines'.
I would like to join the two layers into the 'Image', but this function works only for traslation but not for rotation and scaling.
var saveCanvas = document.createElement('canvas');
var saveContext = saveCanvas.getContext('2d');
saveCanvas.width = Image.width;
saveCanvas.height = Image.height;
saveContext.drawImage(Image,0,0);
saveContext.save();
var t = imageContext.currentTransform;
saveContext.setTransform(1,0,0,1,-t.e,-t.f);
for(var i = 0; i < lines.length; i++){
saveContext.beginPath();
saveContext.moveTo(lines[i].from.X, lines[i].from.Y);
saveContext.lineTo(lines[i].to.X, lines[i].to.Y);
saveContext.stroke();
}
saveContext.restore();
Image.src = saveCanvas.toDataURL();
how can I modify the arguments of 'setTransform' to solve the problem ?
Just use the rest of the transforms attributes.
var t = imageContext.currentTransform;
saveContext.setTransform(
t.a,
t.b,
t.c,
t.d,
-t.e,
-t.f);
Can someone help me to fix the issue?
I want to apply alpha layer mask to make some of the image transparent using canvas.
Thanks a lot.
var redImageData = redCanvas.getContext("2d").getImageData(0, 0, 200, 200); //overlay
var ImageData = imageCanvas.getContext("2d").getImageData(0, 0, 200, 200);
var px = redImageData.data;
var px2 = ImageData.data;
for(var i = 0; i < px.length; i += 4) {
if(px[i + 0] == 0 && px[i + 1] == 0 && px[i+2] == 0){
px[i + 3] = 0;
} else {
px[i + 0] = px2[i + 0];
px[i + 1] = px2[i + 1];
px[i + 2] = px2[i + 2];
px[i + 3] = px2[i + 3];
}
}
ctx.imageSmoothingEnabled = true;
ctx.putImageData(redImageData, 0, 0);
alpha mask overly https://i.stack.imgur.com/zCzOf.png
The linked image is not really an alpha mask but a matte image. The difference is that a matte image represent what would be an alpha-channel but showing it as RGB (or gray-scale) components. It doesn't actually have an alpha-channel. Matte images are common in video-compositing software but not so useful on web.
Canvas, or the Porter-Duff methods it uses, does not support matte images directly so they have to first be converted to an actual alpha-channel. To do this you have to iterate over each pixel and move one of the component values (from red, green or blue - doesn't matter which) into the alpha-channel.
When that is done you can use the canvas object that now has proper alpha-channel with composite operations which only uses the alpha information (blending modes is a different chapter).
The better approach is of course to provide the images as PNG with a proper alpha channel. But in any case, to show it's possible to also work with matte images, although not as efficient, we can do the following:
Converting matte image into alpha channel
First step: this code section shows how you can efficiently do the pre-step of converting the matte image into an alpha channel. The resulting colors are not important for the main compositing step as it will only use the alpha-channel, as already mentioned.
Just make sure the image has loaded properly before trying to use the image by either using the image's onload callback or running the script after everything has loaded.
This code will simply shift a component (blue in this case) using the full 32-bit value of the pixel (for efficiency) into the alpha-channel which leaves the image looking cyan but with proper alpha as you can see with the orange background showing through (most of the code is to handle loading and setup though).
window.onload = function() {
// at this stage the image has loaded:
var img = document.getElementById("img");
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
// - setup canvas to match image
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
// - draw image
ctx.drawImage(img, 0, 0);
// CONV. STEP: move a component channel to alpha-channel
var idata = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data32 = new Uint32Array(idata.data.buffer);
var i = 0, len = data32.length;
while(i < len) {
data32[i] = data32[i++] << 8; // shift blue channel into alpha (little-endian)
}
// update canvas
ctx.putImageData(idata, 0, 0);
};
body {background: #f72; font-size:44px; color:rgba(0,0,0,0.5)}
<img id="img" crossorigin="anonymous" src="https://i.imgur.com/QRGYuWg.png"> ►
<canvas id="c"></canvas>
Compositing
The second part then becomes about compositing using the new alpha-channel.
In this case the matte image's black becomes fully transparent while the white becomes fully opaque. You could have reversed this in the conversion step but it does not really matte as long as you're aware of the how the matte image looks.
To replace the interior content we use compositing mode source-in. This will replace the content depending on the alpha value while keeping the alpha-channel as it is.
Dealing with the interior part first using the same mode allows us to do additional things with the content before drawing the frame (think vignette, shadows etc.).
As the final step we fill in the transparent areas, the frame itself, by using the composite mode destination-over which replaces the more transparent ares with the content being drawn to canvas (conceptually it draws "behind" the existing content).
The code below uses simple colored boxes - just replace those with whatever you want to draw.
window.onload = function() {
var img = document.getElementById("img");
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
ctx.drawImage(img, 0, 0);
var idata = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data32 = new Uint32Array(idata.data.buffer);
var i = 0, len = data32.length;
while(i < len) data32[i] = data32[i++] << 8;
ctx.putImageData(idata, 0, 0);
// COMP. STEPS: use the mask with composite operation. Since our frame
// is black (= transparent as alpha) we can use the following mode:
ctx.globalCompositeOperation = "source-in";
// draw something, here a blue box, replace with whatever you want
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// to fill the frame area, still transparent, use this mode:
ctx.globalCompositeOperation = "destination-over";
ctx.fillStyle = "yellow";
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
body {background: #f72; font-size:44px; color:rgba(0,0,0,0.5)}
<img id="img" crossorigin="anonymous" src="https://i.imgur.com/QRGYuWg.png"> ►
<canvas id="c"></canvas>
I have a large amount of images with a black background, here is one for example:
Is it possible through Javascript to have to ignore the black (#000000) and have it draw on canvas? to appear like this?
Basically trying to take the black pixels and make it an alpha channel.
So you'll need to run through all the pixels and change the alpha value of all the black pixels.
https://jsfiddle.net/0kuph15a/2/
This code creates a buffer (empty canvas) to draw the original image to. Once thats done, it takes all the pixels of this buffer canvas and then iterates over all the pixels and checks their values. I add up the Red, Blue, and Green values to see if they are less then 10 (just incase some pixels aren't pure black 0), but would visually appear black to the human eye. If it is less then 10 it simply turns the alpha value of that pixel to 0.
var canvas = document.getElementById('main');
var ctx = document.getElementById('main').getContext('2d');
var tile = new Image();
tile.src = document.getElementById('image').src;
tile.onload = function() {
draw(tile);
}
function draw(img) {
var buffer = document.createElement('canvas');
var bufferctx = buffer.getContext('2d');
bufferctx.drawImage(img, 0, 0);
var imageData = bufferctx.getImageData(0,0,buffer.width, buffer.height);
var data = imageData.data;
var removeBlack = function() {
for (var i = 0; i < data.length; i += 4) {
if(data[i]+ data[i + 1] + data[i + 2] < 10){
data[i + 3] = 0; // alpha
}
}
ctx.putImageData(imageData, 0, 0);
};
removeBlack();
}
You can easily change this line if(data[i]+ data[i + 1] + data[i + 2] < 10){ to if(data[i]+ data[i+1] + data[i+2]==0){ if you know for a fact only #000 blacks are used.
You can accomplish that using blend modes.
Change the context globalCompositeOperation to screen, and you can get that result. Here's an example:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = new Image();
image.src = "https://images.blogthings.com/thecolorfulpatterntest/pattern-4.png";
image.onload = function() {
context.drawImage(image, 0, 0, canvas.width, canvas.height);
var blackImage = new Image();
blackImage.src="http://www.printmag.com/wp-content/uploads/Sillitoe-black-white.gif";
blackImage.onload = function(){
context.globalCompositeOperation = "screen";
context.drawImage(blackImage, 0, 0, canvas.width, canvas.height);
}
};
<canvas id="canvas" width="300" height="250"></canvas>
<hr/>
<h1>Images used:</h1>
<img src="https://images.blogthings.com/thecolorfulpatterntest/pattern-4.png"/>
<img src="http://www.printmag.com/wp-content/uploads/Sillitoe-black-white.gif"/>
How about saving the picture as an .svg file...from there you can change all colors and other settings
Felipe's answer addressed my issue. Alpha pixel manipulation does not work
(eg, setting every 4th pixel to 0) for preserving alphatransparency with multiple images added into the same context at the same time.
eg:
this.ctx1.putImageData(output, 0, 0); // without setting the context's globalCompositeOperation, this image is written over by the next putImage operation
this.ctx1.putImageData(output, 20, 0);
Go here to review the blending options. https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation