본문 바로가기

html | javascript

html javascript - easing linear

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Easing 00 Linear</title>
</head>
<body onload="load()">
  <script>
    let Linear = function() {
      this.box = {
        x: 0,
        y: 200,
        width: 100,
        height: 50,
        isToLeft: true,
        d: 160,
        t: 0,
        b: 0,
        c: 600 - 100,
        change: 600 - 100,
        type: 0
      }
      this.canvas = null
      this.context = null
    }
    Linear.prototype.init = function(canvas) {
      this.canvas = canvas
      this.context = canvas.getContext("2d")
    }
    Linear.prototype.getEasing = function(t, c, d, b) {
      return t * c / d + b
    }
    Linear.prototype.onFrame = function() {
      this.box.t++
      let t = this.box.t
      this.box.x = this.getEasing(this.box.t, this.box.c, this.box.d, this.box.b)

      if (this.box.x < this.canvas.width - this.box.width) {

      } else {
        this.box.t = 0
        this.box.c = -this.box.change
        this.box.b = this.box.change
      }

      if (this.box.x <= 0) {
        this.box.t = 0
        this.box.c = this.box.change
        this.box.b = 0
      }

      // clear
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)

      this.context.font = '18pt Calibri'
      this.context.fillStyle = 'black'
      this.context.fillText("Linear Tween", 20, 20)

      this.context.font = '14pt Calibri'
      this.context.fillStyle = 'black'
      this.context.fillText("time * change / duration + begin", 20, 48)

      // draw
      this.context.beginPath()
      this.context.fillStyle = 'blue'
      this.context.fillRect(this.box.x, this.box.y, this.box.width, this.box.height)

      let es = this
      window.setTimeout(() => {es.onFrame()}, 1000 / 60)
    }

    function load() {
      let canvas = document.createElement('canvas')
      canvas.width = 500
      canvas.height = 300
      canvas.style.border = 'solid 1px black'
      document.body.appendChild(canvas)

      let lin = new Linear()
      lin.init(canvas)
      lin.box.c = lin.box.change = canvas.width - lin.box.width
      lin.onFrame()
    }
  </script>
</body>
</html>