javascript图形动画设计--以简单正弦波轨迹移动

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Wave 1</title>
    <link rel="stylesheet" href="../include/style.css">
  </head>
  <body>
    <header>
      Example from <a href="http://amzn.com/1430236655?tag=html5anim-20"><em>Foundation HTML5 Animation with JavaScript</em></a>
    </header>
    <canvas id="canvas" width="400" height="400"></canvas>

    <script src="../include/utils.js"></script>
    <script src="./classes/ball.js"></script>
    <script>
    window.onload = function () {
      var canvas = document.getElementById(‘canvas‘),
          context = canvas.getContext(‘2d‘),
          ball = new Ball(),
          angle = 0,
          centerY = 200,
          range = 50,
          xspeed = 1,
          yspeed = 0.05;

      ball.x = 0;

      (function drawFrame () {
        window.requestAnimationFrame(drawFrame, canvas);
        context.clearRect(0, 0, canvas.width, canvas.height);

        ball.x += xspeed;
        ball.y = centerY / 2 + Math.sin(angle) * range;
        angle += yspeed;
        ball.draw(context);
      }());
    };
    </script>
  </body>
</html>

其中util.js

/**
 * Normalize the browser animation API across implementations. This requests
 * the browser to schedule a repaint of the window for the next animation frame.
 * Checks for cross-browser support, and, failing to find it, falls back to setTimeout.
 * @param {function}    callback  Function to call when it‘s time to update your animation for the next repaint.
 * @param {HTMLElement} element   Optional parameter specifying the element that visually bounds the entire animation.
 * @return {number} Animation frame request.
 */
if (!window.requestAnimationFrame) {
  window.requestAnimationFrame = (window.webkitRequestAnimationFrame ||
                                  window.mozRequestAnimationFrame ||
                                  window.msRequestAnimationFrame ||
                                  window.oRequestAnimationFrame ||
                                  function (callback) {
                                    return window.setTimeout(callback, 17 /*~ 1000/60*/);
                                  });
}

/**
 * Cancels an animation frame request.
 * Checks for cross-browser support, falls back to clearTimeout.
 * @param {number}  Animation frame request.
 */
if (!window.cancelRequestAnimationFrame) {
  window.cancelRequestAnimationFrame = (window.cancelAnimationFrame ||
                                        window.webkitCancelRequestAnimationFrame ||
                                        window.mozCancelRequestAnimationFrame ||
                                        window.msCancelRequestAnimationFrame ||
                                        window.oCancelRequestAnimationFrame ||
                                        window.clearTimeout);
}

/* Object that contains our utility functions.
 * Attached to the window object which acts as the global namespace.
 */
window.utils = {};

/**
 * Keeps track of the current mouse position, relative to an element.
 * @param {HTMLElement} element
 * @return {object} Contains properties: x, y, event
 */
window.utils.captureMouse = function (element) {
  var mouse = {x: 0, y: 0, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;

  element.addEventListener(‘mousemove‘, function (event) {
    var x, y;

    if (event.pageX || event.pageY) {
      x = event.pageX;
      y = event.pageY;
    } else {
      x = event.clientX + body_scrollLeft + element_scrollLeft;
      y = event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;

    mouse.x = x;
    mouse.y = y;
    mouse.event = event;
  }, false);

  return mouse;
};

/**
 * Keeps track of the current (first) touch position, relative to an element.
 * @param {HTMLElement} element
 * @return {object} Contains properties: x, y, isPressed, event
 */
window.utils.captureTouch = function (element) {
  var touch = {x: null, y: null, isPressed: false, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;

  element.addEventListener(‘touchstart‘, function (event) {
    touch.isPressed = true;
    touch.event = event;
  }, false);

  element.addEventListener(‘touchend‘, function (event) {
    touch.isPressed = false;
    touch.x = null;
    touch.y = null;
    touch.event = event;
  }, false);

  element.addEventListener(‘touchmove‘, function (event) {
    var x, y,
        touch_event = event.touches[0]; //first touch

    if (touch_event.pageX || touch_event.pageY) {
      x = touch_event.pageX;
      y = touch_event.pageY;
    } else {
      x = touch_event.clientX + body_scrollLeft + element_scrollLeft;
      y = touch_event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;

    touch.x = x;
    touch.y = y;
    touch.event = event;
  }, false);

  return touch;
};

/**
 * Returns a color in the format: ‘#RRGGBB‘, or as a hex number if specified.
 * @param {number|string} color
 * @param {boolean=}      toNumber=false  Return color as a hex number.
 * @return {string|number}
 */
window.utils.parseColor = function (color, toNumber) {
  if (toNumber === true) {
    if (typeof color === ‘number‘) {
      return (color | 0); //chop off decimal
    }
    if (typeof color === ‘string‘ && color[0] === ‘#‘) {
      color = color.slice(1);
    }
    return window.parseInt(color, 16);
  } else {
    if (typeof color === ‘number‘) {
      color = ‘#‘ + (‘00000‘ + (color | 0).toString(16)).substr(-6); //pad
    }
    return color;
  }
};

/**
 * Converts a color to the RGB string format: ‘rgb(r,g,b)‘ or ‘rgba(r,g,b,a)‘
 * @param {number|string} color
 * @param {number}        alpha
 * @return {string}
 */
window.utils.colorToRGB = function (color, alpha) {
  //number in octal format or string prefixed with #
  if (typeof color === ‘string‘ && color[0] === ‘#‘) {
    color = window.parseInt(color.slice(1), 16);
  }
  alpha = (alpha === undefined) ? 1 : alpha;
  //parse hex values
  var r = color >> 16 & 0xff,
      g = color >> 8 & 0xff,
      b = color & 0xff,
      a = (alpha < 0) ? 0 : ((alpha > 1) ? 1 : alpha);
  //only use ‘rgba‘ if needed
  if (a === 1) {
    return "rgb("+ r +","+ g +","+ b +")";
  } else {
    return "rgba("+ r +","+ g +","+ b +","+ a +")";
  }
};

/**
 * Determine if a rectangle contains the coordinates (x,y) within it‘s boundaries.
 * @param {object}  rect  Object with properties: x, y, width, height.
 * @param {number}  x     Coordinate position x.
 * @param {number}  y     Coordinate position y.
 * @return {boolean}
 */
window.utils.containsPoint = function (rect, x, y) {
  return !(x < rect.x ||
           x > rect.x + rect.width ||
           y < rect.y ||
           y > rect.y + rect.height);
};

/**
 * Determine if two rectangles overlap.
 * @param {object}  rectA Object with properties: x, y, width, height.
 * @param {object}  rectB Object with properties: x, y, width, height.
 * @return {boolean}
 */
window.utils.intersects = function (rectA, rectB) {
  return !(rectA.x + rectA.width < rectB.x ||
           rectB.x + rectB.width < rectA.x ||
           rectA.y + rectA.height < rectB.y ||
           rectB.y + rectB.height < rectA.y);
};

其中ball.js

function Ball (radius, color) {
  if (radius === undefined) { radius = 40; }
  if (color === undefined) { color = "#ff0000"; }
  this.x = 0;
  this.y = 0;
  this.radius = radius;
  this.rotation = 0;
  this.scaleX = 1;
  this.scaleY = 1;
  this.color = utils.parseColor(color);
  this.lineWidth = 1;
}

Ball.prototype.draw = function (context) {
  context.save();
  context.translate(this.x, this.y);
  context.rotate(this.rotation);
  context.scale(this.scaleX, this.scaleY);

  context.lineWidth = this.lineWidth;
  context.fillStyle = this.color;
  context.beginPath();
  //x, y, radius, start_angle, end_angle, anti-clockwise
  context.arc(0, 0, this.radius, 0, (Math.PI * 2), true);
  context.closePath();
  context.fill();
  if (this.lineWidth > 0) {
    context.stroke();
  }
  context.restore();
};

时间: 2024-08-26 06:14:29

javascript图形动画设计--以简单正弦波轨迹移动的相关文章

javascript图形动画设计--画简单正弦波

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Rotate to Mouse</title> <link rel="stylesheet" href="../include/style.css"> <style type="text/css"> .dot{ p

HT图形组件设计之道(一)

HT for Web简称HT提供了涵盖通用组件.2D拓扑图形组件以及3D引擎的一站式解决方式.正如Hightopo官网所表达的我们希望提供:Everything you need to create cutting-edge 2D and 3D visualization. 这个愿景从功能上是个相当长的战线,从设计架构上也是极具挑战性的,事实上HT团队是很保守的,我们从不贪多图大,仅仅做我们感觉自己能得更好,能给用户综合体验更佳的功能,在这样理念驱动下我们慢慢形成了这种愿景,慢慢实现了几个有意义

HT图形组件设计之道(二)

上一篇我们自定义CPU和内存的展示界面效果,这篇我们将继续采用HT完成一个新任务:实现一个能进行展开和合并切换动作的刀闸控件.对于电力SCADA和工业控制等领域的人机交互界面常需要预定义一堆的行业标准控件,以便用户能做可视化编辑器里,通过拖拽方式快速搭建具体电力网络或工控环境的场景,并设置好设备对应后台编号等参数信息,将拓扑图形与图元信息一并保存到后台,实际运行环境中将打开编辑好的网络拓扑图信息,连接后台实时数据库,接下来就是接受实时数据库发送过来的采集信息进行界面实时动态刷新,包括用户通过客户

Android Animation (动画设计)

Android Animation(动画设计) 本文主要介绍逐帧动画,补间动画,属性动画 使用简单的图片 1.Bitmap和BitmapFactory 把一个Bitmap包装成BitmapDrawable对象,调用BitmapDrawable的构造器 BitmapDrawable drawable = new BitmapDrawable(bitmap); 获取BitmapDrawable所包装的Bitmap, Bitmap bitmap = drawable.getBitmap(); 2.Bi

[转]Expression Blend实例中文教程(8) - 动画设计快速入门StoryBoard

上一篇,介绍了Silverlight动画设计基础知识,Silverlight动画是基于时间线的,对于动画的实现,其实也就是对对象属性的修改过程. 而Silverlight动画分类两种类型,From/To/By 动画和关键帧动画. 对于Silverlight动画设计,StoryBoard是非常重要的一个功能,StoryBoard不仅仅可以对动画的管理,而且还可以对动画的细节进行控制,例如控制动画的播放,暂停,停止以及跳转动画位置等. 为了简化开发人员和设计人员的设计过程,Blend提供了专门的工具

Silverlight &amp; Blend动画设计系列四:倾斜动画(SkewTransform)

Silverlight中的倾斜变化动画(SkewTransform)能够实现对象元素的水平.垂直方向的倾斜变化动画效果.我们现实生活中的倾斜变化效果是非常常见的,比如翻书的纸张效果,关门开门的时候门缝图形倾斜变换.在Silverlight中实现一个倾斜变化的动画效果是非常简单的,如果利用Blend这种强大的设计工具来实现那更是锦上添花. 倾斜效果的动画应用效果其实非常好看,使用倾斜变换需要注意的有两点:倾斜方向和倾斜中心点.可以以某点为倾斜中心点进行X或Y坐标方向进行倾斜,如下以默认中心店进行的

网页绘制图表 Google Charts with JavaScript #1....好强、好简单啊!

此为文章备份,原文出处(我的网站) 网页绘制图表 Google Charts with JavaScript....好强.好简单啊!#1 http://www.dotblogs.com.tw/mis2000lab/archive/2014/01/23/google_charts-javascript.aspx 今天看见 g+一篇文章 http://inspiredtoeducate.net/inspiredtoeducate/?p=1319 因而发觉这个东西. 我先连到 Google原厂网站,看

非专业码农 JAVA学习笔记 用户图形界面设计与实现-所有控件的监听事件

用户图形界面设计与实现-监听事件 System.applet.Applet (一)用户自定义成分 1.绘制图形 Public voit piant(Ghraphics g){  g.drawLine等图形名称(坐标1234);g.file图形名(坐标123)} 2.设置字体-Font类 (1)定义font:Font myfont=new Font(“字体”,”样式”,字号); 例如:Font myfont=new Font(“宋体”,Font.BOLD,12); (2)引用定义的Font:类/容

HT图形组件设计之道(四)

在<HT图形组件设计之道(二)>我们展示了HT在2D图形矢量的数据绑定功能,这种机制不仅可用于2D图形,HT的通用组件甚至3D引擎都具备这种数据绑定机制,此篇我们将构建一个3D飞机模型,展示如果将数据绑定机制运用于3D模型,同时会运用到HT的动画机制,以及OBJ 3D模型加载等技术细节,正巧赶上刚发布的iOS8我们终于能将基于HT for Web开发的HTML5 3D应用跑在iOS系统了. 首选我们需要一个飞机模型,采用HT for Web构建3D模型可采用API组合各种基础模型的方式,但今天