2createStudio / postcss-sprites

Generate sprites from stylesheets.
MIT License
413 stars 50 forks source link

Has a wrong result when the width and height of node is bigger then its background-image's #87

Closed chancedai closed 7 years ago

chancedai commented 7 years ago

Has a wrong result when the width and height of node is bigger then its background-image's, codepen demo.

Thank you.

vvasilev- commented 7 years ago

Hey @chancedai,

Sorry for the late response. The sprites don't work in such way. You must have an element with correct dimensions. 😄

Please feel free to reopen the issue if have any questions. 😄

chancedai commented 7 years ago

@vvasilev-
Thank you, I have used the 'onUpdateRule' hook to solve this problem, just do not know if there will be other problems.


var getPosition = function(rule) {
    var res = rule.match(/(0|[+-]?(?:\d*\.|)\d+px|left|right)\s+(0|[+-]?(?:\d*\.|)\d+px|top)/i);
    var position = {
        left: 0,
        top: 0
    };
    if (res) {
        if (res[ 1 ] && res[ 2 ]) {
            if ([ 'left', 'right' ].indexOf(res[ 1 ]) !== -1) {
                position.left = (res[ 1 ] === 'left') ? 0 : res[ 1 ];
            } else {
                position.left = parseFloat(res[ 1 ]);
            }
            position.top = res[ 2 ] === 'top' ? 0 : parseFloat(res[ 2 ]);
        }
    }
    return position;
};
var ratio = image.ratio;
var position = getPosition(rule.nodes[ 0 ].value);
var x = image.coords.x - position.left;
var y = image.coords.y - position.top;
var posX = -1 * (x / ratio);
var posY = -1 * (y / ratio);
var sizeX = image.spriteWidth / ratio;
var sizeY = image.spriteHeight / ratio;

comment.cloneAfter({
    type: 'decl',
    prop: 'background-image',
    value: 'url(' + image.spriteUrl + ')'
}).cloneAfter({
    prop: 'background-position',
    value: posX + 'px ' + posY + 'px'
}).cloneAfter({
    prop: 'background-size',
    value: sizeX + 'px ' + sizeY + 'px'
}).cloneAfter({
    prop: 'background-repeat',
    value: 'no-repeat'
});