Flip image in javascript

Image Rollovers

The classic image flip script is one of the most popular pieces of JavaScript on the web. Using this, you can make an image change to a different image on response to the user placing their mouse in a certain position. This is achieved by loading a new image in the original’s place. When used correctly, they can really add a bit of life to a page. You don’t need to have any JavaScript experience to use these scripts; it’s a simple copy ‘n’ paste job.

This page was last updated on 2012-08-21

The Image Flip

Let’s get into the swing of things with an example — pass your mouse over the image below.

This script is easy to configure, only requiring that you put some words in the right places and name your images correctly. To get the effect working, you first need two images. They should have the same dimensions (height and width), and should reside in the same directory. Give them descriptive names, and save the rolled-over version with a 2 at the end of the filename (eg: image2.gif ). This is important. My two images in the flip to the left are called smirk1.gif and smirk2.gif

Читайте также:  Java class init block

Once you have assembled your images, place this JavaScript onto your page. You should put it in the of the document, so that it is already working before it has a chance to be called.

 var revert = new Array(); var inames = new Array('smirk'); // Preload if (document.images) < var flipped = new Array(); for(i=0; i< inames.length; i++) < flipped[i] = new Image(); flipped[i].src +inames[i]+"2.gif"; >> function over(num) < if(document.images) < revert[num] = document.images[inames[num]].src; document.images[inames[num]].src = flipped[num].src; >> function out(num)

This intimidating-looking chunk of code will be able to take care of any and all rollovers you want to set up on the page. Those of you who have frequented the JavaScript tutorials should be able to make some sort of guess at what’s happening here, but for everyone’s benefit, here’s the run-down.

Break it Down One Time

First we define some variables. The revert array will be used a little later on to save the filename of the image we want to return to when the effect ends. The inames array is used to store the names of all the images that we want to flip — entries should be encased in single-quotes and separated by commas.

Next comes the preload code, which automatically loads the images that are going to be called by the script. These need to be ready to go when the script calls them, as otherwise there’ll be a downloading pause before the image flips. We simply go through the inames array and, for each image, load its flipped version in the background. These images are stored in the browser’s cache, ready to leap into the fray. I keep my images in the folder media/ — you should change this to whatever your folder is named.

Читайте также:  Не нажимается ссылка html

sourcetip: Your images, especially the one that appears during the flip, will have to load very quickly if the effect is going to be a success. Even with the built-in pre-load, you must still keep them small by optimising them down.

Finally we have the two functions that will do all the magic, over and out . Each image object has the modifiable property src , the image’s filename. When the user places their mouse on the image, over is called. Once the support detection is done, it saves the file’s current src value into a slot in revert . It then changes the src value to the preloaded version we have ready. The images will switch.

Once the user then moves their mouse back off the image, we want it to change back to its original value, which we cunningly saved for this purpose into the revert variable. So, the out function merely reassigns the image’s src value to this filename, and the image returns to its initial state. Ace.

Inserting the Images

Right, so that’s the script sorted out, now we just need to add the images. This is done like any other image, but with some extra JS attributes thrown in:

This HTML creates the image. The script will then wait for the user to trigger it. The onMouseOver event handler ‘listens’ for certain user actions; in this case their mouse passing over the image. When this happens it fires the over function, and sends the image’s number along with it. It’s the first rollover image on the page so it sends a 0. The second image would send a 1 etc. Always remember, the first object in an array is numbered with a zero.

When the user’s mouse moves away from the image again, onMouseOut notices and fires out , again adding in the image’s number so the function knows which image it has to work on.

Filenames

The name attribute we add to our images should be exactly the same as the names we gave the image in the inames array in the script. This is used to construct the rolled-over image’s filename. If we call our first image smirk , as I have done, the script decides that the corresponding rolled-over filename will be media/smirk2.gif . The initial image can be called anything you want, but it would be a good idea to name it similarly to the second, ending with a 1.

Multiple Rollovers

Expanding the script’s usefulness to many rollovers on the same page is easy — you simply add a new entry to the inames array and then send a different number with the functions. So, to add a second rollover, one line in the script will need to be modified:

var inames = new Array('smirk', 'smile');

The image code will be similar:

That’s it. Each new rollover image just needs a new entry in inames and the correct number to be sent with the functions.

Changing Multiple Images Together

You can even set it up so that two or more images change at a time. This is achieved easily too — by simply executing the over and out functions repeatedly for each event. Because each image has a unique index in the inames array, they will not interfere with each other. Mousing over the following link would change the first two rollover images on the page simultaneously, and then switch them both back on MouseOut — also demonstrating how the image itself does not have to be the triggering element.

In a similar fashion, you can also get the image to change onClick , though this is rarely used as the event doesn’t last very long.

Keep Learning // Image Maps → Go! Go!

Источник

Flipping Images Horizontally Or Vertically With CSS And JavaScript

In this 3 minute article we’ll look at flipping images horizontally and vertically using CSS and JavaScript. We’ll explore how to flip an img element, a background-image , or flip the actual ImageData using a canvas element.

Flipping an Image Element

We can flip the img element using the CSS transform property. We can do so using the scaleX and scaleY transforms.

img src="/media/tulips.jpg" alt="" />
img  /* flip horizontally */ transform: scaleX(-1); > img  /* flip vertically */ transform: scaleY(-1); > img  /* flip both */ transform: scale(-1, -1); >

original

scaleX(-1)

scaleY(-1)

scale(-1, -1)

Alternatively you can use rotateX and rotateY

img  /* flip horizontally */ transform: rotateY(180deg); > img  /* flip vertically */ transform: rotateX(180deg); > img  /* flip both */ transform: rotateX(180deg) rotateY(180deg); >

original

rotateY(180deg)

rotateX(180deg)

rotateX(180deg)
rotateY(180deg)

The rotation transform is also a nice choice for when you want to animate the flip.

scaleX

rotateY

Note that I’ve added a slight perspective to the transform chain. Without the perspective transform the rotateY animation would be just as flat as the scaleX animation. I’ve added it to the scaleX animation as well to show that it doesn’t make a difference.

@keyframes flip-with-scale  0%  transform: perspective(400px) scaleX(1); > 100%  transform: perspective(400px) scaleX(-1); > > @keyframes flip-with-rotate  0%  transform: perspective(400px) rotateY(0); > 100%  transform: perspective(400px) rotateY(180deg); > >

Flipping a Background Image

The only way (at this point in time) (and as far as I can tell) to flip a background-image is to flip the element containing the background image. But that would flip its contents as well.

p class="tulips"> Tulips form a genus of spring-blooming perennial herbaceous bulbiferous geophytes. p>
.tulips  background-image: url(/media/tulips.jpg); background-repeat: no-repeat; background-size: contain; padding-left: 5em; > .tulips-flipped  transform: scaleX(-1); >

Tulips form a genus of spring-blooming perennial herbaceous bulbiferous geophytes.

Tulips form a genus of spring-blooming perennial herbaceous bulbiferous geophytes.

To work around this we can either move the background to a separate element or create a pseudo-element.

Let’s go with the pseudo-element.

.tulips  display: flex; width: 15em; > /* create our pseudo element */ .tulips-flipped::before  content: ''; background-image: url(/media/tulips.jpg); background-repeat: no-repeat; background-size: cover; min-width: 5em; > /* flip our pseudo element */ .tulips-flipped::before  transform: scaleX(-1); >

Tulips form a genus of spring-blooming perennial herbaceous bulbiferous geophytes.

Tulips form a genus of spring-blooming perennial herbaceous bulbiferous geophytes.

Flipping an Image with JavaScript

The CSS flipping techniques only alter the presentation of an image, not the actual pixel data. We can flip the pixel data using the canvas element. This might be useful if for example we want to flip an image before it’s uploaded to a server.

We’ll use the image data in the image element below the code snippet, it’s simply an img tag with a class name set to image-tulips .

img src="/media/tulips.jpg" class="image-tulips" alt="" />

Lets get a reference to the image. That allows us to load it to a canvas element for manipulation.

const inputImage = document.querySelector('.image-tulips'); // need to check if the image has already loaded if (inputImage.complete)  flipImage(); > // if not, we wait for the onload callback to fire else  inputImage.onload = flipImage; > // this function will flip the imagedata function flipImage()  // create a canvas that will present the output image const outputImage = document.createElement('canvas'); // set it to the same size as the image outputImage.width = inputImage.naturalWidth; outputImage.height = inputImage.naturalHeight; // get the drawing context, needed to draw the new image const ctx = outputImage.getContext('2d'); // scale the drawing context negatively to the left (our image is 400 pixels wide) // resulting change to context: 0 to 400 -> -400 to 0 ctx.scale(-1, 1); // draw our image at position [-width, 0] on the canvas, we need // a negative offset because of the negative scale transform ctx.drawImage(inputImage, -outputImage.width, 0); // insert the output image after the input image inputImage.parentNode.insertBefore( outputImage, inputImage.nextElementSibling ); >

The above code just ran, and you can view the result below. The first image is the inputImage and the second image is the outputImage canvas element.

Conclusion

We learned three methods to flip images for various purposes. We can flip images using the CSS transform property. The scaleX and scaleY transforms work but the rotateX and rotateY transforms allow for nicer animation (if needed). We quickly explored flipping background images using pseudo elements and ended the article with manipulating the actual image data using JavaScript and a canvas element.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

At PQINA I design and build highly polished web components.

Make sure to check out FilePond a free file upload component, and Pintura an image editor that works on every device.

Источник

How to Draw a Flipped or Mirrored Image with the HTML Canvas and JavaScript?

yellow Labrador puppy on floor

Sometimes, we want to draw a flipped or mirrored image with the HTML canvas and JavaScript.

In this article, we’ll look at how to draw a flipped or mirrored image with the HTML canvas and JavaScript.

Draw a Flipped or Mirrored Image with the HTML Canvas and JavaScript

To draw a flipped or mirrored image with the HTML canvas and JavaScript, we can call drawImage with the width multiplied by -1 and the scale method.

to add the canvas element.

const canvas = document.querySelector('canvas') const context = canvas.getContext('2d') const img = new Image() img.src = 'https://i.picsum.photos/id/943/200/200.jpg?hmac=cFvTm_QTKVRRCLsOsMx1m2RmksDL0_U5AfcmnQ7TVds' img.onload = () =>

to select the canvas with document.querySelector .

Then we call getContext to get the context.

Next, we use the Image constructor to create an img element.

And then we set the src property of the img element to the URL of the image.

Then we set img.onload to a function that draws the image when the image is loaded.

We call scale with -1 and 1 to flip the image.

Then we call drawImage with the img image, the x and y coordinates of the top left corner, and the width and height of the image respectively.

Now we see the flipped image drawn on the screen.

Conclusion

To draw a flipped or mirrored image with the HTML canvas and JavaScript, we can call drawImage with the width multiplied by -1 and the scale method.

Источник

Оцените статью