Make image face movement direction html - javascript

I am trying to make an image face the direction it moves. For example, the player presses "up" and the image faces up. How would I achieve this?
Code:
Javascript
function move_img(str) {
var step=10;
switch(str){
case "down":
var x=document.getElementById('braum').offsetTop;
x= x + step;
document.getElementById('braum').style.top= x + "px";
break;
case "up":
var x=document.getElementById('braum').offsetTop;
x= x -step;
document.getElementById('braum').style.top= x + "px";
break;
case "left":
var y=document.getElementById('braum').offsetLeft;
y= y - step;
document.getElementById('braum').style.left= y + "px";
break;
case "right":
var y=document.getElementById('braum').offsetLeft;
y= y + step;
document.getElementById('braum').style.left= y + "px";
break;
}
}
Code:HTML
<img src=images/braum.png id='braum' style="position:absolute; left: 500; top: 100;">
<br><br><br><br>
<input type=image onClick=move_img('up') src="images/uparrow.png">
<br>
<input type=image onClick=move_img('left') src="images/leftarrow.png">
<input type=image onClick=move_img('right') src="images/rightarrow.png"'>
<br>
<input type=image onClick=move_img('down') src="images/downarrow.png">
</body>
</html>
Thanks for your help!

Generally your algorithm is right, but, you have many problems with your syntax and organization
you should wrap onclick value with quotation mark > onclick="move_img('...')"
In your inline CSS - you are missing px unit, so it should be > left: 500px; top: 100px
In your right button - you have an extra apostrophe in the end (before the ending > sign
Though not completely wrong, in some cases - offsetLeft and offsetTop differ from top and left - so it is not wise to use them together
In order to change the rotation you should use the transform CSS property, in order to access it by JS use element.style.transform - the value is rotate(Xdeg) where X is the degrees that you want to rotate the element by
This is a working example for such thing (I made some changes to the HTML because I don't have the images, but the logic stays the same):
function move_img(side){
var step = 10;
var element = document.getElementById('braum');
var left = parseInt(element.style.left);
var top = parseInt(element.style.top);
var rotation = 0;
switch(side){
case 'up': top-=step; rotation = -90; break;
case 'right': left+=step; rotation = 0; break;
case 'left': left-=step; rotation = 180; break;
case 'down': top+=step; rotation = 90; break;
}
element.style.top = top+'px';
element.style.left = left+'px';
element.style.transform = 'rotate('+rotation+'deg)';
}
#braum{
width: 40px;
height: 40px;
color: white;
text-align: center;
transition: transform 0.5s; /* Remove This to remove the animation */
background: green;
position:absolute;
}
<div id='braum' style="left: 100px; top: 100px;">Hi</div>
<input type="button" onclick="move_img('up')" value="up" >
<input type="button" onclick="move_img('left')" value="left" >
<input type="button" onclick="move_img('right')" value="right" >
<input type="button" onclick="move_img('down')" value="down" >

Related

Moving a rectangle up down left and right

I wanted to make a rectangle move in 4 directions with a click of a button on JavaScript. Only the Right and Down works and the other two does not work. I tried finding it on internet and so far had not have any luck.
var currentXpos = 0;
function moveRectRight() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}
function moveRectDown() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}
#rectangle {
background-color: red;
width: 200px;
height: 100px;
margin-left: 0px;
}
<div id='rectangle'></div>
<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />
Your problem lies on this code
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginRight = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginBottom = currentXpos + 'px'; // re-draw rectangle
}
when you move left you tried to add the margin right and when you move up you add margin bottom. This is a wrong concept, you shouldn't imagine it like the box is being pushed from 4 side like this image
When you code in HTML & CSS, try to imagine that in coordinate, the 0,0 (x and y) is on your upper left corner of browser, and to move them you can only move them away or closer to the 0,0, like below
I suggest you to learn/debug using the developer tools you can see where it goes wrong,
So the answer is just changing the code to marginLeft and marginTop
That aside, I made my own version maybe you want to check it out
<html>
<head>
<style>
#rectangle {
background-color: red;
width: 200px;
height: 100px;
position: fixed;
}
</style>
</head>
<body>
<div id='rectangle' style="top:100px;left:100px;"></div>
<input type="button" value="Right" onclick="moveRect(this)" />
<input type="button" value="Left" onclick="moveRect(this)" />
<input type="button" value="Up" onclick="moveRect(this)" />
<input type="button" value="Down" onclick="moveRect(this)" />
<script>
const distance = 10;
const directionMap = {
'Up': {
'prop': 'top',
'value': -1
},
'Down': {
'prop': 'top',
'value': 1
},
'Left': {
'prop': 'left',
'value': -1
},
'Right': {
'prop': 'left',
'value': 1
},
}
const parsePosition = (prop) => parseFloat(rectangle.style[prop]) || 0;
const moveRect = (element) => {
let {
prop,
value
} = directionMap[element.value];
rectangle.style[prop] = (parsePosition(prop) + (value * distance)) + "px";
}
</script>
</body>
</html>
Because margins in the HTML, depend on having a neightbor. So, you'll not see margin-right and margin-bottom working, hence you'll not see the box going up or left.
Instead, what you can do, is affect the same property with addition and substraction. For Y affect only margin-top and for X affect only margin-left
CSS Documentation
<html>
<head>
<style>
#rectangle {
background-color: red;
width: 200px;
height: 100px;
margin-left: 0px;
}
</style>
</head>
<body>
<div id='rectangle'>
</div>
<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />
<script>
var currentXpos = 0;
function moveRectRight() {
var rect = document.getElementById('rectangle');
console.log(rect)
currentXpos += 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos -= 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentXpos -= 100; // move by 100 px to the right
rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}
function moveRectDown() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginTop = currentXpos + 'px'; // re-draw rectangle
}
</script>
</body>
</html>
Thremulant gave a very good solution but there was something missed something the "current position" variable should be different for X and Y axis. This way it will not show abnormal behaviour.
<html>
<head>
<style>
#rectangle {
background-color: red;
width: 200px;
height: 100px;
margin-left: 0px;
}
</style>
<script>
var currentXpos = 0;
var currentYpos = 0;
function moveRectRight() {
var rect = document.getElementById('rectangle');
currentXpos += 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectLeft() {
var rect = document.getElementById('rectangle');
currentXpos -= 100; // move by 100 px to the right
rect.style.marginLeft = currentXpos + 'px'; // re-draw rectangle
}
function moveRectUp() {
var rect = document.getElementById('rectangle');
currentYpos -= 100; // move by 100 px to the right
rect.style.marginTop = currentYpos + 'px'; // re-draw rectangle
}
function moveRectDown() {
var rect = document.getElementById('rectangle');
currentYpos += 100; // move by 100 px to the right
rect.style.marginTop = currentYpos + 'px'; // re-draw rectangle
}
</script>
</head>
<body>
<div id='rectangle'></div>
<input type="button" value="Right" onclick="moveRectRight()" />
<input type="button" value="Left" onclick="moveRectLeft()" />
<input type="button" value="Up" onclick="moveRectUp()" />
<input type="button" value="Down" onclick="moveRectDown()" />
</body>
</html>

create a div with a text where i click an image

I have an image in HTML and i want the user to write an input in HTML and then if he click on the image it will create a colored div which is written inside the input, the position of this div is based of the coordinates where the user clicked (not centered, a little on top and to the left), for now I can create the rectangular div, but i don't know how to put a text in it.
let listaAre = [];
let quantiClic = 0;
document.getElementById('blah').addEventListener('click', event => {
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;"></div>';
document.getElementById('squar' + quantiClic).style.top = (event.pageY - Number(document.getElementById('dimensione').value) / 2) + 'px';
document.getElementById('squar' + quantiClic).style.left = (event.pageX - Number(document.getElementById('dimensione').value) / 2) + 'px';
document.getElementById('squar' + quantiClic).style.width = Number(document.getElementById('dimensione').value)/4 + 'px';
document.getElementById('squar' + quantiClic).style.height = Number(document.getElementById('dimensione').value)/10 + 'px';
document.getElementById('squar' + quantiClic).style.background =(document.getElementById('colorebordo').value);
listaAre.push({
x: (event.offsetX - Number(document.getElementById('dimensione').value) / 2),
y: (event.offsetY - Number(document.getElementById('dimensione').value) / 2),
width: Number(document.getElementById('dimensione').value),
height: Number(document.getElementById('dimensione').value),
background:(document.getElementById('colorebordo').value)
});
document.getElementById('squar' + quantiClic).addEventListener('click', function (e) {
this.style.display = 'none';
});
quantiClic = quantiClic + 1;
});
article, aside, figure, footer, header,
hgroup, menu, nav, section { display: block; }
.fasciaalta {
position: fixed;
background-color: white;
}
<div class="fasciaalta">
<input type="color" id="colorebordo">
<input type="text" id="nome">
<input type="number" id="dimensione" value="200">
<hr size="2px" color="blue" width="100">
</div>
<img id="blah" src="montagna.jpg" alt="your image" />
<div id="squareContaine"></div>
<div id="previewImage"></div>
You can get the coordinates of the mouse on the event click by accessing the clientX and clientY properties of the event object. Then you simply tell the new element to use them as top and left styles to position it.
Snippet
document.getElementById('blah').addEventListener('click', function(event) {
var div = document.createElement("DIV"); // Create a <div> element
var t = document.createTextNode("HELLO");// Create a text node
div.appendChild(t); // Append the text to <div>
document.body.appendChild(div); //Add <div> to document
div.style.position = 'absolute'; //Make its position absolute
//Set the coordinates
div.style.left = event.clientX + "px";
div.style.top = event.clientY + "px";
})
<div>
<img id="blah" src="http://img1.wikia.nocookie.net/__cb6/nyancat/images/5/50/Wiki-background" alt="your image" />
</div>
Extra
If instead of creating a new div, you want to use one simply access that element with getElementById and change its properties instead. I've made the example as simple as possible so that it can apply to not only your case but anyone else's trying to solve their issue.
If you need the text value then all you need is to change the first 2 statements of your click function. - Check this Codepen
1) Onclick, get the value of the textbox like so
var val = document.getElementById('nome').value;
2) Next insert this val into your innerHTML statement
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;">'+ val + '</div>';
Scroll the very end of the above statement to see the val inserted.
Also do not forget to change the color of the text if the background of the box is black.
document.getElementById('blah').addEventListener('click', event => {
var val = document.getElementById('nome').value; //added
//below statement changed
document.getElementById('squareContaine').innerHTML =
document.getElementById('squareContaine').innerHTML +
'<div id="squar' + quantiClic + '" style="background-color: blue; height: 50px; width: 50px; position: absolute;">'+ val + '</div>';
.. rest of the code remain the same ..
});

How do I get the change picture arrows to be on the sides of the picture?

So I have a picture slideshow that has arrow buttons that allow the user to go to the next or last image. How do I get these arrows to be on or in the picture on the appropriate side (left middle for previous image and right middle for next image)?
Here is my current code:
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
setInterval(displayNextImage, 6000);
}
function startUp(){
document.getElementById("img").src = images[0];
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
</script>
</head>
<body onload = "startTimer(); startUp()">
<button type="button" onclick="displayPreviousImage()"> &laquo</button>
<img id="img" style="width:500px;height:380px;" src="startpicture.jpg">
<button type="button" onclick="displayNextImage()"> &raquo</button>
</div>
</body>
Wrap your image in a container to get an HTML structure like this:
<div class="imgContainer">
<button class="leftButton"></button>
<img class="slideshowImage">
<button class="rightButton"></button>
</div>
Then apply CSS such as this one:
.imgContainer {
position: relative;
}
.leftButton {
position: absolute;
left: 0; bottom: 50%;
}
.rightButton {
position: absolute;
right: 0; bottom: 50%;
}
By specifying the position property of your buttons to be absolute, you're making them position themselves relative to their closest parent with an absolute or relative position.
This is why we set .imgContainer's position to relative.
We can now position the buttons within the container with the left, right, top and bottom properties.
Check this article for a more in-depth explanation: Absolute Positioning Inside Relative Positioning.
Perfect vertical centering of the buttons is more tricky and requires yet another hack so for now you can just use the bottom: 50%;, or dive into the art of Centering in CSS when you feel ready.

Image zoom in and out with respect to the centre of div not working

I have an image zoom property in one of my website.I want to zoom an image with respect to the centre of the div.
<div class="img"><img src="http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/men-wedding-rings.jpg" /></div>
<input class="beta" type="button" onclick="zoom(1.1)" value="+">
<input class="beta" type="button" onclick="zoom(0.9)" value="-">
And the zoom funcction is as follows.
function zoom(zm)
{
img=document.getElementById("pic")
wid=img.width
ht=img.height
img.style.width=(wid*zm)+"px"
img.style.height=(ht*zm)+"px"
}
I want to zoom the image with respect to the centre.
Thanks in advance.
How about this http://jsfiddle.net/sajith/J6Y3X/
JS
function zoom(zm) {
img = document.getElementById("pic")
wid = img.width
ht = img.height
img.style.width = (wid * zm) + "px"
img.style.height = (ht * zm) + "px"
img.style.marginLeft = "-" + (wid * zm)/2 + "px"
img.style.marginTop = "-" + (ht * zm)/2 + "px"
}
CSS
.img {
width:450px;
height:450px;
}
#pic {
position: absolute;
left: 225px;
top: 225px;
margin: -225px 0 0 -225px;
}
HTML
<div class="img"><img id="pic" src="http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/men-wedding-rings.jpg" /></div>
<input class="beta" type="button" onclick="zoom(1.1)" value="+">
<input class="beta" type="button" onclick="zoom(0.9)" value="-">

Fix a zoom in and out coding

I am using the following coding
<html>
<head>
<style>
#thediv {
margin:0 auto;
height:400px;
width:400px;
overflow:hidden;
}
img {
position: relative;
left: 50%;
top: 50%;
}
</style>
</head>
<body>
<input type="button" value ="-" onclick="zoom(0.9)"/>
<input type="button" value ="+" onclick="zoom(1.1)"/>
<div id="thediv">
<img id="pic" src="http://upload.wikimedia.org/wikipedia/commons/d/de/Nokota_Horses_cropped.jpg"/>
</div>
<script>
window.onload = function(){
zoom(1)
}
function zoom(zm) {
img=document.getElementById("pic")
wid=img.width
ht=img.height
img.style.width=(wid*zm)+"px"
img.style.height=(ht*zm)+"px"
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}
</script>
</body>
</html>
For making a simple zoom in and zoom out function.
I this i have a difficulty of the image is zooming indefinitely. i want to fix a position to zoom in and zoom out. The image must not exceed that position while zooming in and zooming out.
I am adding a fiddle to this link
Here you go:
var zoomLevel = 100;
var maxZoomLevel = 105;
var minZoomLevel = 95;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel++;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel--;
}else{
return;
}
}
wid = img.width;
ht = img.height;
img.style.width = (wid*zm)+"px";
img.style.height = (ht*zm)+"px";
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}​
You can modify the zoom levels to whatever you want.
I modified the fiddle a bit, since you only need to add javascript to the bottom-left area.

Categories

Resources