How to show packed sprites with CSS and scale them

July 11, 2022

Example:

 

 


Reactjs component and calculations:

import React from 'react';

type props = {
    width: number,
    height: number,
    frame: { x: number, y: number, w: number, h: number },
    textureUrl: string,
    background?: string,
};

class TextureImageResizeComponent extends React.Component<props> {

    render() {
        let {
            width,
            height,
            background,
            frame,
            textureUrl,
        } = this.props;


        if (width === 0) {
            width = frame.w;
        }

        if (height === 0) {
            height = frame.h;
        }

        return (
            <div style={{
                width: width,
                height: height,
                position: 'relative',
                background: background,
            }}>
                <div style={{
                    backgroundImage: 'url(' + textureUrl + ')',
                    width: frame.w,
                    height: frame.h,
                    backgroundPosition: '-' + frame.x + 'px -' + frame.y + 'px',
                    backgroundRepeat: 'no-repeat',
                    display: 'inline-block',
                    transform: 'scale(' + (width / frame.w) + ', ' + (height / frame.h) + ')',
                    top: 0,
                    left: 0,
                    marginTop: ((height - frame.h) / 2),
                    marginLeft: ((width - frame.w) / 2),
                    position: 'absolute',
                }}>

                </div>
            </div>
        );
    }
}

export default TextureImageResizeComponent;

tags: ,
posted in games, js, Reactjs by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org