Spawn a image on another image giving a coordinate - javascript

I have some image coordinates and I want to use them to put a small image on those with javascript. Can this be accomplished with javascript or I need to create the div and modify it's css attributes? By the way: the image can be placed anywhere on the page.

Here is a fully working code: Live Demo
CSS
.overlays{
position:absolute;
}
JS
function showImage() {
// myImage : ID of image on which to place new image
var image = document.getElementById('myImage');
console.log(image.width);
margin = 20;
l = image.offsetLeft;
t = image.offsetTop;
w = image.width;
h = image.height;
// Location inside the image
offX = parseInt(Math.random() * w);
offY = parseInt(Math.random() * h);
if(offX > margin) offX -= margin;
if(offY > margin) offY -= margin;
l += offX;
t += offY;
var newImage = document.createElement("img");
newImage.setAttribute('src', '1.jpg');
newImage.setAttribute('class', 'overlays');
newImage.style.left = l + "px";
newImage.style.top = t + "px";
document.body.appendChild(newImage);
}

Try this to place the new image on coordinates (X,Y) of a parent image:
var newImg = document.getElementById('newImg'), // your new (small) image
img = document.getElementById('parentImg'); // parent image
document.body.insertBefore(newImg, img); // Insert the new image before the image
document.body.insertBefore(img, newImg); // Then switch places (So the small image is after the big one in the DOM)
newImg.style.position = 'relative';
newImg.style.left = X + "px";
newImg.style.top = (Y - img.height)+"px"; // Substract the height of the source image to get the position relative to the top left.
The double insertBefore is to insert the new image after the bid one, by first inserting it before the big one, then moving the big one in front of it.
Then, it's just a matter of setting the new image's coordinates relative to the big image.
Working Example (Set to display the overlay after 2 seconds to show the difference)

css:
#yourId{
position: absolute;
}
js:
var img = document.getElementById('yourId'), // or any other selector
x = x, // your data
y = y; // your data
img.style.left = x+"px";
img.style.top = y+"px";

Related

I made a script that detects if there is white space surrounding an image and automatically removes it, sometimes, it still leaves some of it

The code is a simple image cropper that allows the user to select an image file, crop the image to remove any surrounding white space, and then download the resulting cropped image.
My problem is that sometimes the code leaves a little bit of white space around some images and i don't have any idea on why it does that.
Here is my code:
// Add an event listener to the file input field to process the selected file
document
.getElementById("fileInput")
.addEventListener("change", function () {
// Get the file object
var file = this.files[0];
// Create a FileReader object
var reader = new FileReader();
// Add an event listener to the FileReader object to process the file when it's loaded
reader.addEventListener("load", function () {
// Create an image object and set its src to the data URL of the file
var img = new Image();
img.src = this.result;
// Wait for the image to load
img.onload = function () {
// Get the width and height of the image
var width = img.naturalWidth;
var height = img.naturalHeight;
// Create a canvas element and draw the image onto it
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
// Get the image data of the canvas
var imageData = ctx.getImageData(0, 0, width, height);
var data = imageData.data;
// Iterate through the image data and determine the edges of the non-white pixels
var top = height;
var bottom = 0;
var left = width;
var right = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var index = (y * width + x) * 4;
if (
data[index] !== 255 ||
data[index + 1] !== 255 ||
data[index + 2] !== 255
) {
// This pixel is not white, so update the edges if necessary
top = Math.min(top, y);
bottom = Math.max(bottom, y);
left = Math.min(left, x);
right = Math.max(right, x);
}
}
}
// Calculate the dimensions of the cropped image
var croppedWidth = right - left;
var croppedHeight = bottom - top;
// Create a second canvas element and draw the cropped image onto it
var croppedCanvas = document.createElement("canvas");
croppedCanvas.width = croppedWidth;
croppedCanvas.height = croppedHeight;
var croppedCtx = croppedCanvas.getContext("2d");
croppedCtx.drawImage(
img,
left,
top,
croppedWidth,
croppedHeight,
0,
0,
croppedWidth,
croppedHeight
);
// Get the data URL of the cropped image and set it as the href of the download link
var downloadLink = document.getElementById("downloadLink");
downloadLink.href = croppedCanvas.toDataURL();
// Set the download attribute of the link to the file name of the original image
downloadLink.download = file.name;
// Set the src of the cropped image element to the data URL of the cropped image
var croppedImage = document.getElementById("croppedImage");
croppedImage.src = croppedCanvas.toDataURL();
};
});
// Read the file as a data URL
reader.readAsDataURL(file);
});
I tried adding a little bit of white tolerance but it seems not to fix the problem.

I am having trouble with my javascript animation

I am trying to animate using a sprite sheet and use it in my website, however I am knew to animation and I am having some trouble fixing it, currently nothing shows up on my webpage when I use this. I am using a sprite sheet which is called Speech.png, is 18176 x 256 and each frame is 256x256. Here is my code so far.
<script language="javascript">
// screen size variables
var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight;
var canvas = document.createElement('canvas');
var c = canvas.getContext('2d');
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
var xpos=0,
ypos=0,
index=0,
numFrames = 70,
frameSize= 255;
// Add our drawing canvas
document.body.appendChild(canvas);
//load the image
image = new Image();
image.src = "Speech.png";
image.onload = function() {
//we're ready for the loop
setInterval(loop, 1000 / 30);
}
function loop() {
//clear the canvas!
c.clearRect(0,0, SCREEN_HEIGHT,SCREEN_WIDTH);
/*our big long list of arguments below equates to:
1: our image source
2 - 5: the rectangle in the source image of what we want to draw
6 - 9: the rectangle of our canvas that we are drawing into
the area of the source image we are drawing from will change each time loop() is called.
the rectangle of our canvas that we are drawing into however, will not.
tricky!
*/
c.drawImage(image,xpos,ypos,frameSize,frameSize,0,0,frameSize, frameSize);
//each time around we add the frame size to our xpos, moving along the source image
xpos += frameSize;
//increase the index so we know which frame of our animation we are currently on
index += 1;
//if our index is higher than our total number of frames, we're at the end and better start over
if (index >= numFrames) {
xpos = 0;
ypos = 0;
index = 0;
//if we've gotten to the limit of our source image's width, we need to move down one row of frames
} else if (xpos + frameSize > image.width){
xpos =0;
ypos += frameSize;
}
}
</script>

How to position one image by appending in a div in random positions but within a specific width and height by javascript?

I want to position append an image inside a div. The image should be displayed 5 times within a height of 500 and width of 500. They should be positioned randomly be in different places but they should not cross the height and width of the div.But my code produces a result where the images are always positioned in an inclined line right to left and always creating faces which are together.
Here's my code:
var theLeftSide = document.getElementById("leftSide");
var top_position = Math.random() * 500 - 100;
var left_position = Math.random() * 500 - 100;
numberOfFaces = 5;
function generateFaces() {
for (var i = 0; i < 6; i++) {
createElement(i);
numberOfFaces += numberOfFaces;
}
}
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
top_position += 20;
left_position += 20;
}
The images are being placed in a diagonal line becauset you are incrementing top_position and left_position by 20 every call. Basically you pick a random start, e.g. 10, 15, for smiley one. Then smiley two gets placed at 30, 45, smiley three at 50, 65, etc. To fix this you need to regenerate both positions for every image.
The following code will do what you want. I added getRandomInt from MDN (here) to make it a little easier to get a number you want.
var theLeftSide = document.getElementById("leftSide");
var top_position;
var left_position;
numberOfFaces = 5;
function generateFaces() {
for (var i = 0; i < 6; i++) {
top_position = getRandomInt(0, 500);
left_position = getRandomInt(0, 500);
createElement(i);
numberOfFaces += numberOfFaces;
}
}
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
Keep in mind this does not respect the bounds of the div. For that you would have to set the div's position to relative, set a width and height, and update this code to get the divs dimentions (for example, using the answer here). The images should be positioned based on their top left corner so you would also need to subtract the width and height of the image from the width and height used to generate the random position numbers to prevent images from overflowing on the bottom or right.

How to get images from a texture atlas with Javascript?

A spritesheet image object that contains sprites...
var spritesheet = new Image(); spritesheet.src ="foo.png";
I would like to be able to get a sub image from that spritesheet variable with the desired x, y, width, and height. And then assign a variable that is the sub image of the spritesheet.
How do I do that?
Using a div with backgroundPosition makes this easy since it will auto-clip for us without having to use overflow.
For example, here is the texture atlas from the popular Cookie Clicker idle game.
Using a negative offset for x and y we can select a sub-sprite from the texture atlas:
// Inputs -- change this based on your art
var tw = 48; // Texture Atlas Tile Width (pixels)
var th = 48; // Texture Atlas Tile Height (pixels)
var tx = 3; // tile index x (relative) (column)
var ty = 2; // tile index y (relative) (row)
var src = 'http://orteil.dashnet.org/cookieclicker/img/icons.png';
// Calculations -- common code to sub-image of texture atlas
var div = document.getElementById('clip');
var x = (tx*tw); // tile offset x position (absolute)
var y = (ty*th); // tile offset y position (absolute)
div.style.width = tw + 'px';
div.style.height = th + 'px';
div.style.backgroundImage = "url('" + src + "')";
div.style.backgroundPosition = '-' + x + 'px -' + y + 'px';
// You don't need the remaining parts. They are only to
// show the sub-sprite in relation to the texture atlas
div.style.border = "1px solid blue"; // only for demo purposes
// highlight where in the original texture the sub sprite is
var rect = document.getElementById('sprites').parentNode.getBoundingClientRect();
var hi = document.getElementById('highlight');
hi.style.zIndex = 999; // force to be on top
hi.style.position = "absolute";
hi.style.width = tw + 'px';
hi.style.height = th + 'px';
hi.style.left = (rect.left + x) + 'px';
hi.style.top = (rect.top + th + y) + 'px'; // skip sub-sprite height
hi.style.border = '1px solid red';
<div id="clip"></div>
<img id="sprites" src="http://orteil.dashnet.org/cookieclicker/img/icons.png">
<div id="highlight"></div>
Here's one way:
Create an in-memory canvas to clip the subsprite pixels from the spritesheet and draw those clipped pixels on that canvas
Create a new subsprite image from that canvas's dataURL.
Example code (not tested--may need tweeking):
var spritesheet = new Image();
spritesheet.onload=function(){
// specify desired x,y,width,height
// to be clipped from the spritesheet
var x=0;
var y=0;
var w=10;
var h=10;
// create an in-memory canvas
var canvas=document.createElement('canvas');
var ctx=canvas.getContext('2d');
// size the canvas to the desired sub-sprite size
canvas.width=w;
canvas.height=h;
// clip the sub-sprite from x,y,w,h on the spritesheet image
// and draw the clipped sub-sprite on the canvas at 0,0
ctx.drawImage(spritesheet, x,y,w,h, 0,0,w,y);
// convert the canvas to an image
var subsprite=new Image();
subsprite.onload=function(){ doCallback(subsprite); };
subsprite.src=canvas.toDataURL();
}
spritesheet.src ="foo.png";
function doCallback(img){
// do something with the new subsprite image
}

Javascript: edit an images height in a for loop

I'm trying to edit an images height that is repeating in a for loop in javascript but I can't figure out where I would need to add it in.
Here are the variables if it's important:
var i;
var start = 1;
var seg = document.getElementById("selSegs").value;
var parent = document.getElementById("divInch"), //parent for appendChild
imagePath = 'InchwormSegment.gif', //variable for image
img; //adding img element
Here is my loop:
for(i = start; i<=seg; i++) {
img = new Image(); //creating new image object
img.src = imagePath; // element src = imagePath
img.style.height = "215px"; // sets the height of all in loop
// img.style.height = (img.style.height * .9) + "px"; - does nothing
parent.appendChild(img); //appendChild adds another child (img) object
}
I've tried adding in some math but I just can't figure out where it is supposed to go
Let me know if this fiddle accomplishes what you are trying to do: http://jsfiddle.net/AyNY5/. A few things to remember:
You can edit the image "height" attribute directly, no need to go through style (You don't even need to add px!)
Don't use new Image() - use document.createElement('img'). That's the W3C supported standard.
If I'm off let me know - otherwise, you were on the right track!
JS Code in Fiddle:
var parent = document.getElementById("imgholder")
for (i=0;i<3;i++) {
var img = document.createElement('img');
img.src = "http://bit.ly/1975WKA"
img.height = "200"
parent.appendChild(img)
}
At this point image does not have style.height assigned. It does have height attribute though.
Instead of
img.style.height = (img.style.height * .9) + "px";
try
img.style.height = (img.height * .9) + "px";

Categories

Resources