Home > Software design >  Get sprite sheet background position?
Get sprite sheet background position?

Time:07-12

I have a table where each cell background is populated by sprites from a sprite sheet when the user clicks the cell which applies a class.

#design_container td {
  border: solid 1px #333;
  border-width: 0 1px 1px 0;
  width: 15px;
  height: 15px;
  background-image: url("../img/material_sprite.png");
  background-repeat: no-repeat;
}
.material_58 {
  background-position: -192px -48px;
}

Now I am using html5 canvas to make a download image. How can I get the background-position of the cells? I tried(and failed)

let x = document.querySelector('.material_58').style.backgroundPosition;
console.log(x); // returned nothing/blank

And also to no avail:

let tmp = window.getComputedStyle(x,null).backgroundPosition.trim().split(/\s /);

I assume they may be getting the background position of the actual element, not the position of the sprite sheet. I'm trying to get

background-position: -192px -48px;

If something like that doesn't work maybe something like get the actual class description and parse it? Thank you for your help.

CodePudding user response:

The issue with your approach is that you're referencing a nonexistent style attribute on the element. What you want is the computed style:

const element = document.querySelector('.material_58');
const bgpos = getComputedStyle(element).backgroundPosition;

console.log(bgpos);
.material_58 {
  background-position: -192px -48px;
}
<div ></div>

It would work the way you have it if the background position were inline:

console.log(
  document.querySelector('.inline-style')
    .style
    .backgroundPosition
);
<div  style="background-position: -192px -48px"></div>

  • Related