简体   繁体   中英

Declaring a single image from a sprite sheet in javascript

I'm trying to define and declare an image from a sprite sheet in javascript. I've defined the image within an external style sheet as follows:

#myimage{ background-position: 0 -751px; width: 21px; height: 21px; }

.dwg { background:url(spriteSheet.png) no-repeat;}

I've tried various arrangements similar to the following, none of which, of course, works.

myimage=new Image();
myimage.src="background:url('spriteSheet.png') 0 0; width: 35px; height: 16px;  no-repeat";

I use the image as follows:

document.stat.src = myimage.src;

My Javascript conditional logic switches between various images depending upon status. The code has worked fine with individual images, but I have combined them into a sprite sheet and now need to assign individual images from the sheet. And in order to do so, I need to define each image as a JavaScript variable.

What should be inserted in place of the background: url... string?

A few months I a started using the following approach and it became the easiest to me:

JS code:

    $('[class*=sprite-]').each(function(){
        var crr = this.className.match(/sprite\-(\d+)\-(\d+)/);
        if ( crr && crr[2]) {
            $(this).css('background-position', '-'+ crr[1] +'px -'+ crr[2] +'px');
            $(this).addClass('sprite');
        }
    });

CSS code:

.sprite {
    border: none;
    background-color: transparent;
    background-image: url(your-sprite-image.gif);
    background-repeat: no-repeat;
}

HTML code (You may replace "50x50" by your sprite coordinate):

<img class="sprite-50-50" width="100" height="200" src="use-a-blank-image.gif" alt="" >

I am not 100% sure what you are trying to do because the code is a little weird. The src attribute is the src of the image. If you are doing a sprite... then you should probably be using a div tag, not even using an img. Sprites are usually not "img" tags, but usually "div" tags that are formatted to show just a single frame of your sprite sheet using a background-image. You would only need to adjust the background properties of the div using backgroundImage and backgroundPosition properties and show the sprite you have created. There is no reason to create an Image object in javascript and try to apply it to your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM