简体   繁体   English

在html5 / javascript画布中向上移动的动画元素

[英]Animating element to move up in html5/javascript canvas

I am making simple animations in JavaScript html canvas. 我在JavaScript html canvas中制作简单的动画。 Currently I have a function which makes the element (image) fall infinitely down. 目前,我有一个函数可以使元素(图像)无限下降。 I would like to reverse it and make it go infinitely up (start at the bottom of the page and move up and up and up), but all my attempts and experiments failed. 我想反转它并使它无限上升(从页面底部开始,然后向上和向上移动),但是我的所有尝试和实验都失败了。
I would be grateful for any ideas! 我将不胜感激任何想法!

This is the function I have, which moves the element down: 这是我拥有的功能,可将元素向下移动:

function moveDown(){
    start += 1;
    var m = document.getElementById('money');
    m.style.top = start + "px";
    m.style.left = "300px";

}
var start = 350;


function rain() {

    var m = document.createElement('img');
    m.id = "money";
    m.src = "images/holof.png";
    m.style.position = "absolute";
    m.style.top = start + "px";
    // m.style.top="0px";
    m.style.left = "300px";
    m.setAttribute("class", "money");
    document.body.appendChild( m );

    setInterval(moveDown, 500);



}

How do I animate it to go up then? 那我该如何使其动画呢?

I'm not sure what this has to do with canvas but you can simply do the following for your Image element to move upwards. 我不确定这与画布有什么关系,但是您可以简单地执行以下操作以使Image元素向上移动。

Reverse your start increment to a decrement 将起始增量反转为减量

function moveUp(){

    start--;   /// move up 1 pixel

    style.top = start + "px";
}

var start = 350;
var m = document.getElementById('money'); /// cache this here
var style = m.style;                      /// cache style
style.left = "300px";                     /// set once here

The caching will improve the performance as it reduces the talkativeness between JS and the DOM. 缓存将降低JS和DOM之间的健谈性,从而提高性能。

However, as a tip: when the element has moved out of sight you will want to stop the loop as otherwise you will do unnecessary code invoking so adding a condition in there to stop the loop is something to consider. 但是,提示:当元素移出视线时,您将要停止循环,否则将执行不必要的代码调用,因此要在其中添加条件以停止循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM