Overlaying image in HTML - javascript

I am creating a simple interactive doll dress up game where the user can pick different attributes to assign to the doll through three separate drop down menus, such as hair colour, dress type, etc.
I have a base image that is in a div which I want to overlay the images onto.
<div id="display_here">
<img src="base.png" />
</div>
The images are called by a function:
function createDoll(userChoice) {
var output = document.getElementById("display_here");
output.innerHTML = "";
var links = [
"redhair.png",
"blondehair.png",
"brownhair.png",
];
var choices = ["Red", "Blonde", "Brown", "Vintage", "Skater", "Plaid", "Heels", "Brogues", "Pumps"];
var img = '<img src="' + links[userChoice] + '">';
output.innerHTML = img;
}
I have given each option in the select menu a value which corresponds to the value in var choices, here is the hair colour option:
<p>
What hair will your doll have?
<select name="choice" id="choice" onchange="createDoll(this.value)">
<option value="0">Red</option>
<option value="1">Blonde</option>
<option value="2">Brown</option>
</select>
</p>
So for each option I want it to overlay onto the base image but nothing I have tried seems to work. The only thing I seem to be able to find on this is the 'position:relative' and 'position:absolute' solution but since my images are not in a div this won't work. Can anybody thing of anything that might work?

The first thing I notice is output.innerHTML = "";, which will get rid of your base.png image. I assume this is something that you don't want to do.
So, one way to handle this is to have all the images that you might need already there, but keep them hidden or with an empty src attribute until needed.
<div class="overlay-container">
<img class="overlay" src="base.png">
<img class="overlay" id="hair">
<img class="overlay" id="clothing1">
<img class="overlay" id="clothing2">
</div>
Then in your function, you could do something like this.
function createDoll(userChoice) {
var links = [
"redhair.png",
"blondehair.png",
"brownhair.png"
];
document.getElementById('hair').src = links[userChoice];
}
As for taking care of the overlaying, you'll need to use an absolute position with z-indexing on each image inside of a div with relative positioning. For example, here is some CSS styling that reflects this.
.overlay { position: absolute; }
.overlay-container { position: relative; }
#hair { z-index: 10; }
#clothing1 { z-index: 20; }
#clothing2 { z-index: 21; }
To make positioning easier, I recommend keeping most of your similar images, such as different hair types, all of the same size, otherwise you'll have to give different top and left CSS styling co-ordinates for each one. Of course, the simplest option is to just make all of the different images the same size.
I hope this has been of some help, and good luck!

You should be able to use absolute positioning to make it work, since everything lives in the 'display_here' div.
You could also use HTML5 Canvas to draw the clothes onto the doll as well. Seems like a perfect opportunity to use it.

Related

use JavaScript to toggle between different "crops" of a single large image

So I have been reading up on dozens upon dozens of Javascript zoom components, but none of them do what I am looking for, so I'm curious where to find such a component (if one exists) or how to code it myself.
The goal is to download a single large (1000x1000) image to the browser. Then within the browser, the image would have three presentation states within the same element container that the user can toggle between by clicking on some page element.
State 1 (default): See the entire image, but scaled down to fit within a 500x500 container (i.e. shrunk, but not cropped). For example (not to scale, but for comparison with other states):
State 2: See the middle 50%, centered, in the same container (i.e. actual size, and cropped). For example:
State 3: See the middle 25%, centered, in the same container (i.e. enlarged, and cropped quite a bit). For example:
And I would put the script that toggles between these three states in the click of some page element, such as a button.
Can any one offer a link to a component that does this, or suggestions on how the method that might accomplish it?
Thanks for any help!
I will go down on leveraging some CSS here.
For first case:
1) create a DIV which is 500x500, and set the background image to the file. Make sure you set background-size:contain property as well on the div.
2) For the second case I will remove the background-size:contain
3) The third case I will set the `background-size:200%;'
JSFiddle
If what you've described is really all you want to do it can be easily achieved with some CSS and a few lines of javascript:
var container = document.querySelector('.image-zoom'),
zoomBtn = document.getElementById('zoom-it'),
i = 0;
function clickHandler() {
if (i === 0) {
container.classList.add('zoom-2x');
i++;
} else if (i === 1) {
container.classList.add('zoom-4x');
i++;
} else {
container.classList.remove('zoom-2x');
container.classList.remove('zoom-4x');
i = 0;
}
}
zoomBtn.addEventListener('click', clickHandler);
.image-container, .image-zoom {
width: 250px;
height: 250px;
}
.image-container {
overflow: hidden;
}
.image-zoom.zoom-2x {
transform: scale(2);
}
.image-zoom.zoom-4x {
transform: scale(4);
}
<div class="image-container">
<div class="image-zoom" style="background-image:url(http://lorempixel.com/250/250)">
</div>
</div>
<button id="zoom-it">zoom image</button>
This assumes you know the dimensions of the image, which if you're using a CMS you can likely easily get and insert them inline on the .image-zoom and .image-containerelements.
jsFiddle
EDIT
jsFiddle 2
Modified the jsfiddle to be closer to what your question asked (initial state of the image is contained within the square and not cropped any amount.)

slideshow using html not working

I have gone through the answer posted earlier on this website but my slideshow does not work and shows the first image always.
Below is my code
<div id= slideshow>
<img class ='imagem_artigo' src="/images1/coveover.jpg" name="Myslide" width=750; height=300 align="middle">
<script type="text/javascript">
var step = 1;
var img1 = new Image();
img.src = "/images1/tecover.jpg";
var img2 = new Image();
img2.src = "/images1/te.jpg";
var img3 = new Image();
img3.src = "/images1/te1.jpg";
var img4 = new Image();
img4.src = "/images1/im7.jpg";
function slideshow(){
document.images.Myslide.src = eval("img" + step+".src");
if(step<=4)
step++;
else
step = 1;
setTimeout(function(){slideshow()},1000);
}
slideshow();
</script >
</div>
When building sliders it's better to write the majority of what you want to show in the DOM so it'll load and search engines can find it etc.
Here's what I would do
<div id="imageSlider">
<div class="imageSliderContainer clearfix">
<div class="article">
<img src="/images1/coverover.jpg" width="" height="" alt="write stuff here etc" title="">
</div>
<div class="article">
<img src="/images1/tecover.jpg" width="" height="" alt="" title="">
</div>
<div class="article">
<img src="/images1/te.jpg" width="" height="">
</div>
<div class="article">
<img src="/images1/te1.jpg" width="" height="">
</div>
<div class="article">
<img src="/images1/im7.jpg" width="" height="">
</div>
</div>
</div>
using alt and title will mean your html will be wc3 compliant ;) also the image can be found using an internet search :) or whatever
Now you wanna build a slideshow huh? I'll show you some cool CSS to get you going first then I'll come back to the javascript :p
first off, we want to make sure people who haven't got javascript enabled are able to view your images don't we? So lets make a nice scroll window looking thingy for those special paranoid people with no javascript :p
#imageSlider{overflow:auto;}
Now anything that's over 100% width of #imageSlider will be scrollable.
I've used classes called articles. The reason I've done this will become much clearer later :) but for now this is simply why.
There are 5 articles and you want each to be 100% of the parent so that the others aren't showing when you're on that image right? So 5*100=500
.imageSliderContainer{width:500%;}
100/5=20
.imageSliderContainer .article{width:20%;float:left;}
.clearfix:after{clear:both;display:block;visibility:hidden;content:'';}
Now each article/image will be 100% width of the parent so they won't be visible when one is selected :p
and the clearfix and float will make the articles inline with each other :) without causing conflicts with other elements
Next we want to make sure our images look cool inside the article. and they're properly positioned and sized so they're not outside of the container etc.
.imageSliderContainer .article img{max-width:100%;height:auto;display:inline-block;}
.imageSliderContainer .article{width:20%;text-align:center;background:#000000;}
now things should be starting to look rather nice and smooth right? IF you're still following :p
Next comes the javascript. I'm more fluent in jQuery but I'll give examples of both just incase :)
First off we want to turn off the scrolling
$('#imageSlider').css({'overflow':'hidden'});/*jquery*/
document.getElementById('imageSlider').style.overflow="hidden";/*javascript*/
Next we want to make the images 'change' when really what I'm going to do is scroll the element along so we can see the next one ;p
Some people like to use a negative margin left but some designers are like "AGHHHH NEGATIVE VALUES" for some reason so I'll just use scrollLeft instead :p
this is where it's ganna get a little complicated. First you want to get the current location of the container's scrollLeft then adjust it.
/*jQuery*/
function nextSlide(){
var sliderScroll=$('#imageSlider').scrollLeft();
var artWid=$('.article').width();
var artQuant=$('.article').length;
var next=0-(sliderScroll==((artQuant-1)*artWid))?0(sliderScroll+artWid);
$('#imageSlider').animate({scrollLeft:next},500);
}
/*javascript*/
function nextSlideA() {
var slider=document.getElementById('imageSlider');
var art=document.getElementsByClassName('article');
var next=0-(slider.scrollLeft==((art.length-1)*art[0].offsetWidth()))?0:(art[0].offsetWidth()+slider.scrollLeft);
document.getElementById('position').innerHTML=next;
slider.scrollLeft = next;
}
the variable next will equal 0 if you're on the last image and will go to the next image if you're in the middle of the slideshow :)
Javascript won't look as fancy as jQuery but it'll get the job done. I'm sorry if I've made any mistakes I'm currently on the phone as I'm writing this, let me know if something doesn't work and I'll fix it :)
Next just simply call the function using your setInterval();
var slider=setInterval(function(){nextSlide();},1000);
And job done :) Hope this was helpful! I'll make a quick jsfiddle for you so you can see how it all works :)
http://jsfiddle.net/s6crzzfr/

Protecting an Image from downloading by Right-Click

EDIT: In response to many comments I do know that there is no sure fire way to fully protect an image from being downloaded. This method is to prevent the casual user from downloading by simple right click. The best way probably would be simply copyrighting your images and if you are very concerned would be using a service like Digimarc to digitally watermark your image. Now to the question:
I came across a site that is using a GIF overlay over their actual image so it protects the image from users right clicking and downloading the image (though you can still grab the actual image from within the code). The code they use to do this is:
<div><img src="-Transparent GIF File-" alt="" width="530" height="558"
border="0" original="-Actual Image Displayed-" /></div>
My question is the original tag is not a real tag and is used and translated by Javascript of some sort. I would like to replicate this on my site. Can someone help me find this script?
This is pointless. If a browser displays an image, it can be taken. Any attempt to prevent that is merely site overhead that can very easily be circumvented.
You're best protection is to put a copyright notice on the images themselves.
In any event, if you really want to swap the original attribute you can...
$(function() {
var o = $('img').attr('original');
$('img').attr('src', o);
});
Demo here
but... that doesn't do anything to prevent the user selecting and saving the image tied tot eh original attribute.
A simpler solution for what you're trying to accomplish is to add all of these attributes to the img tag:
ondrag="return false"
ondragstart="return false"
oncontextmenu="return false"
galleryimg="no"
onmousedown="return false"
Also, to optionally make the image print smaller, add this to the img tag:
class="imgPrint"
And include this related CSS:
#media print
{
.imgPrint
{
width: 40%;
}
}
You can do this without original tag also :
http://rainbow.arch.scriptmania.com/scripts/no_right_click.html
see this link.
I think this is what u want, this link may help you.
This is my implementation for a light protection of images.
It will create a transparent cover DOM element over the image (or text). If you disable javascript the image will be hidden and if you remove the cover the image will be hidden on mouse over. Also right click on images is disabled.
You can always printscreen, grab from the downloaded resources, etc, etc. This will only filter the most basic ways of download. But for a more convenient protection you have to hide the image path and render to a canvas object.
You can improve this, but there is always a method to get the image.
Tested on major browsers and working!
HTML
<div class="covered">
<img src="image.jpg" alt="" />
</div>
JAVASCRIPT + JQUERY
$('.covered').each( function () {
$(this).append('<cover></cover>');
$(this).mousedown(function(e){
if( e.button == 2 ) {
e.preventDefault();
return false;
}
return true;
});
$('img', this).css('display', 'block');
$(this).hover(function(){
var el = $('cover', this);
if (el.length <= 0) {
$(this).html('');
}
});
});
CSS
cover
{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.covered
{
position: relative;
}
.covered img
{
display: none;
}

Positioning Divs semi-randomly, without overlaps

I have a page which has DIVs which contain short phrases (one-two words) of varying font sizes, which need to be positioned left-to-right according to a numerical parameter, and vertically so as not to overlap.
It's like a tag cloud, but there's information contained in the y-axis as well ("coolness" in this case - http://cool-wall.appspot.com)
How should I lay these out? I'm currently using a very messy series of DIVs like this:
<div style="position:absolute; top:150px;left:10px;right:10px;bottom:10px">
<!-- then, repeated, with different top, left and font-size values -->
<div style="align:center; margin:0; border:none; padding:0; float:left; visibility:visible; position:absolute; top:21%; left:56%; font-size:11px">
<div style="margin-top:0%; margin-right:50%; margin-bottom:0%; margin-left:-50%;">
<span style="display:inline"> ← </span>
<span style="display:inline"> Buzz </span>
<span style="display:inline"> → </span>
</div>
</div>
<!-- of course, followed by a close div -->
</div>
I use a stylesheet to extract some of those styles, and I realise that it's pretty poor CSS (and HTML)... but this was all I could hack together to do (almost) what I wanted to do. The main problem with the above (apart from it being confusing) is that I can't set the positioning so it doesn't overlap, because I don't know what size the font will be, nor how it will display onscreen.
Happy to use JavaScript to get it right. But I don't know where to start. Any tips?
There is a javascript property on the dom object that will tell you the height of the tag if you have the width set. I believe its called clientHeight
alert(document.getElementById('myElement').offsetHeight);
Try that (also see http://www.webdeveloper.com/forum/archive/index.php/t-121578.html)
OR
Try this
<span style="margin-top:${randomNumber}px;margin-bottom:${randomNumber}">randomtext</span>
<span style="margin-top:${randomNumber}px;margin-bottom:${randomNumber}">randomtext</span>
..
<span style="margin-top:${randomNumber}px;margin-bottom:${randomNumber}">randomtext</span>
Have all your element just display inline, output them in random order, and then set random margin's on them. This could all be done with server side code (or javascript if you want it client side).
The x-value is set on each one, you want to be as high on the page as possible (lowest y) as it can go without overlapping. Not too bad:
1) Render the container - position:relative; Render each item inside the container with "position:absolute; top:0; left:-1000; " - draw them all off screen.
2) One by one, move the element to it's needed x-coorinate and y=0; Check it with all previous render items to see if it collides, if it does, move it down one pixel until it doesn't collide:
var regions = [];
for(var i = 0; i < items.length; i++){
var item = items[i];
item.style.x = getX(item); // however you get this...
var region = YAHOO.util.Dom.getRegion(item);
var startingTop = region.top;
for(var iReg = 0; iReg < regions.length; iReg++){
var existingRegion = regions[iRegion];
while(region.intersect(existingRegion)){
region.top++;
region.bottom++;
}
item.style.y = (region.top - startingTop) + 'px';
}
}
It's important to just update the region and not actually move the dom node 1px at a time for performance reasons.
Put most important items first and they will render with more priority than items below them.
Don't position your elements absolutely. This is the reason they are falling on top of each other....

Rotating Div using javascript

Here is a link: http://www.avineon.com/
Open this link see on the top. Four images are rotating.
I need something similiar using Javascript.
Is it possible by using Javascript.
I don't think you'll have much luck if you try to do that in pure javascript. It might be possible using the emerging canvas and SVG libraries such as Raphael, but you'll still have cross-browser issues. That site used Flash, and I'd recommend using that if you wanted such an effect.
...why you'd want that on your website is another story though...
You could so something similar, but not exact.
Transparency = Supported in FF, Safari, IE7+
Changing image width = Place image in div with this Css
.class img {
display: block;
width: 100%;
height: 100%
}
This will make the image stretch to fill the .class div. You can then use JS to make this div narrower like the carousel does, and the image contained will animate within the div.
You would then need to track the mouse locations to determine how fast it spins.
You can use an equation using cosine for smooth acceleration from the far ends (IIRC)
You will not however be able to get the images in reverse, unless you create a copy in a server side language or use canvas.
Your best bet would not be to attempt to render something in actual 3D, but rather to use visual tricks to approximate a 3D effect. That is, use perspective / image deformation to make it look like a cube is rotating, similar to what is implemented at this page, which has a better explanation of the math involved.
Really, though, you're probably better off just using Flash.
That effect is possible in JavaScript simply by modifying each of the images width, height, and left styles over time. It's an involved script, but only needs to interpolate those three styles on the each of the image elements.
To get the rotation effect, decrement the width style of the image in a setInterval function while moving the left style property. There is a slight decrement on the height also.
You'll need two images for each side, a front and reverse. When the width decrements to zero, swap the image with it's flipped version and start incrementing the width.
Alternatively use Webkit's, and Firefox's transform css properties.
Or try one of these coverflow components that look similar:
Protoflow,
ImageFlow
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">\n');
document.write('.dyncontent{display: none; width: 728px; height: 90px;}\n');
document.write('</style>');
}
var curcontentindex=0;
var messages=new Array();
function getElementByClass(classname){
var inc=0;
var alltags=document.all? document.all : document.getElementsByTagName("*");
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
messages[inc++]=alltags[i];
}
}
function rotatecontent(){
//get current message index (to show it):
curcontentindex=(curcontentindex<messages.length-1)? curcontentindex+1 : 0;
//get previous message index (to hide it):
prevcontentindex=(curcontentindex==0)? messages.length-1 : curcontentindex-1;
messages[prevcontentindex].style.display="none"; //hide previous message
messages[curcontentindex].style.display="block"; //show current message
}
window.onload=function(){
if (document.all || document.getElementById){
getElementByClass("dyncontent");
setInterval("rotatecontent()", 5000);
}
}
</script>
<table width="100%">
<tr align="center">
<td>
<div class="dyncontent" style="display: block">
first
</div>
<div class="dyncontent">
second
</div>
<div class="dyncontent">
Third
</div>
</td>
</tr>
</table>
</body>
</html>

Categories