Reputation: 39
Hey guys i'm currently working on a small game and i've been trying to use css to flip horizontally an image like so:
JS
sprite = new Image(13, 32);
sprite.src = w1.png;// stored locally i know but i dont intend to sell this:)
if (player.velX < 0) {
sprite.setAttribute("class", "flip")
if (player.velX > 0) {
sprite.removeAttribute("class", "flip")
CSS
.flip {
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
}
so is the problem the fact that i'm creating the img element in JS ?
(btw i use functions to change the sprite's src somewhere else in the code is that the problem ? (do you need some of that code too ?)
Upvotes: 0
Views: 125
Reputation: 4049
Based on the indentation and bracket placement of your code, this is currently what's it doing:
if the velocity is less than 0 then
add the flip attribute to the image
if the velocity is more than 0 then // This can't happen
remove the flip attrbiute from the image
endif
endif
You probably wanted to put both of them on the same level like:
if the velocity is less than 0 then
...
endif
if the velocity is more than 0 then
...
endif
In JS this is:
if (player.velX < 0) {
sprite.classList.add("flip"); // Use classList.add instead of setAttribute
// There's no real reason to this, except that it was specifically designed
// for this. You wouldn't use a pencil to dig a hole in a wall, right?
}
if (player.velX > 0) {
sprite.classList.remove("flip"); // Same reason as above
}
Upvotes: 1
Reputation: 308
Use sprite.classList.add('flip')
or sprite.classList.remove('flip')
rather than changing the class attribute on the element.
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
Upvotes: 0