JS new Image()没有得到css类

时间:2016-10-25 20:40:47

标签: javascript html css canvas

嘿伙计们,我目前正在开发一款小游戏,而且我一直试图用css水平翻转图像:

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);
}

问题是我在JS中创建img元素的事实吗?

(顺便说一句,我使用函数来改变代码中其他地方的sprite&s src是问题吗?(你还需要一些代码吗?)

2 个答案:

答案 0 :(得分:1)

根据您的代码的缩进和括号位置,这是它目前正在做的事情:

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

您可能希望将它们放在同一级别上,如:

if the velocity is less than 0 then
    ...
endif

if the velocity is more than 0 then
    ...
endif

在JS中,这是:

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
}

答案 1 :(得分:0)

使用sprite.classList.add('flip')sprite.classList.remove('flip')而不是更改元素的class属性。

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList