1. 程式人生 > >【動畫】簡易製作貝塞爾曲線動畫(JS+css3+canvas)

【動畫】簡易製作貝塞爾曲線動畫(JS+css3+canvas)

一些廢話(直接看程式碼的可跳過)

貝塞爾曲線:什麼是貝塞爾曲線?用過PS的就知道,那破鋼筆工具就是,什麼,沒用過?自行百度用法。
貝塞爾曲線

需要的工具

  • ctrl+c、ctrl+v

直接上程式碼

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style>
      body {
        position: fixed;
        background: black
; }
#flower { border: 1px solid red; width: 500px; height: 500px; position: relative; }
</style> </head> <body> <div id="flower"></div> </body> <script> (function (data) { var _methods = { // 初始化
init: function () { this.data = data.data this.e = data.e this.count = data.number this.color = data.color // number = 度數° --- this.count = 迴圈次數 this.number = 360 / this.count for (var i = 0, j = .1; i < this.count; i++, j += .1
) { var canvas = document.createElement('canvas') canvas.id = 'flower' + i canvas.height = data.height canvas.width = data.width canvas.style.position = 'absolute' canvas.style.transition = j + 's ease' this.$(this.e).appendChild(canvas) // 繪圖 this.painting(this.$('flower' + i)) } // 動畫 this.handle() }, // 繪圖 painting: function (e) { var ctx = e.getContext("2d") ctx.beginPath() // ----起始座標(x, y) ctx.moveTo(this.data.start.x, this.data.start.y) // ----曲線座標(x, y)--結束座標(x, y) ctx.quadraticCurveTo(this.data.curve.x, this.data.curve.y, this.data.end.x, this.data.end.y) /* 軸對稱 --- 只針對曲線左到右 */ ctx.moveTo(this.data.start.x, this.data.start.y) ctx.quadraticCurveTo(this.data.start.x + this.data.curve.x, this.data.curve.y, this.data.end.x, this.data.end.y) ctx.fillStyle = this.color ctx.strokeStyle = this.color ctx.globalAlpha = 0.1 ctx.fill() ctx.stroke() }, // 動畫 handle: function () { var self = this var i = 0 var timer = setInterval(function () { if (i > self.count) { clearInterval(timer) return } self.$('flower' + i).style.transform = 'rotate(' + i * self.number + 'deg)' i++ }) }, $: function (dom) { return document.getElementById(dom) } } _methods.init() })({ /* 配置項 */ e: "flower", height: 500, width: 500, color: '#cc00ff', data: { // ----起始座標(x, y) start: { x: 250, y: 0 }, // ----曲線座標(x, y) curve: { x: 125, y: 125 }, // ----結束座標(x, y) end: { x: 250, y: 250 } }, // 數量 number: 15 })
</script> </html>

過渡中的動畫

過渡中的動畫

結束的動畫

簡單解釋

1)座標解釋

// ----起始座標(x, y)
start: {
  x: 250,
  y: 0
},
// ----曲線座標(x, y)
curve: {
  x: 125,
  y: 125
},
// ----結束座標(x, y)
end: {
  x: 250,
  y: 250
}

這裡真的是坑走多了得出的結論,稍微要解釋的就是中間的曲線座標,他就是兩點之間的曲線角度

2)Y軸的坑

所有的Y軸為頂點到底部的距離值非左下角原點

3)過程解釋

init(初始化遍歷生成Dom結構並執行painting繪圖Canvas)
handle(生成動畫)

一個完整的DEMO

關於

make:o︻そ╆OVE▅▅▅▆▇◤(清一色天空)

結束語

什麼,你說有啥用?這難道不像你的菊花嗎?^_^哈哈……開玩笑
你試著修改下曲線任意的值看看效果,不夠?那你修改下原始碼,增加下顏色的隨機性試試?