【问题标题】:JS new Image() doesnt get css classJS new Image() 没有得到 css 类
【发布时间】:2016-10-26 04:53:28
【问题描述】:

大家好,我目前正在开发一款小游戏,我一直在尝试使用 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 元素的事实吗?

(顺便说一句,我在代码中的其他地方使用函数来更改精灵的 src 是这个问题吗?(你也需要一些代码吗?)

【问题讨论】:

  • 您是否在任何地方将sprite 插入到 DOM 中?
  • 我真的希望你关闭两个 if 语句
  • 是的,我的更新函数使用 requestanimationframe 并且我绘制了播放器(我可以看到播放器在向左移动时不会翻转它)
  • 另外,在你的 if 语句中,如果 player.velx 为 0 会发生什么?
  • @Bálint 或者没有打开它们{...相信删除左括号添加一个右括号会起作用。

标签: javascript html css canvas


【解决方案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
}

【讨论】:

  • 一开始它实际上是在 if/else if 中(对不起,我丢失了该代码并试图从内存中引用它)
  • @War10ck 我这样做是为了让初学者更容易理解(因为它是英文),但是好的,我包含了一个 js sn-p
  • 好的,我马上回来试试 编辑:试过了,仍然没有明显的变化,我把它添加到更新函数的末尾,同样的代码,问题在于精灵。 src 被代码修改了? (也在更新之外尝试过)
  • 哇哈哈实际上这要简单得多:所以我正在查看您的代码,我注意到您正在使用画布 API 绘制精灵(这是一个好主意)。问题是您不能将 CSS 应用于绘制到画布上的图像。查看此问题以了解如何翻转画布中的内容。 – Mike C 但仍然感谢您的回答:)
  • @poolmatho 您可能想将其发布到其他地方
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-12-28
    • 2019-12-30
    • 1970-01-01
    • 2018-01-12
    • 2014-10-18
    • 1970-01-01
    • 2012-01-03
    • 2011-12-10
    • 1970-01-01
    相关资源
    最近更新 更多