#情人節專題#利用Three.js實現一個記錄兩個人走過歲月的點點滴滴的idea

Luxm發表於2019-02-14

前言

碰巧我們在一起兩週年,花了兩天碼了一個走心的禮物,於是就有了這個小專案的來源

首先看下效果圖---一個音樂播放,帶圖片切換的時間記錄器

#情人節專題#利用Three.js實現一個記錄兩個人走過歲月的點點滴滴的idea

專案地址github.com/jackluson/t…

如果覺得不錯的話,您可以點右上角 "Star" 支援一下 謝謝! ^_^

技術實現

  • 雪花飄落效果實現

    1.把五張圖片充當雪花,然後three.js3D庫 + 定時 營造出雪花飄落的效果,大致程式碼如下:

    function init() {
        camera = new THREE.PerspectiveCamera(75, containerWidth / containerHeight, 1, 10000);
        camera.position.z = 1000;
        scene = new THREE.Scene();
        scene.add(camera);
        renderer = new THREE.CanvasRenderer();
        renderer.setSize(containerWidth, containerHeight);
        for (var i = 0; i < snowNum; i++) {
          var material = new THREE.ParticleBasicMaterial({
            map: new THREE.Texture(particleImages[i % 5])
          });
          particle = new Particle3D(material);
          particle.position.x = Math.random() * 2000 - 1000;
          particle.position.y = Math.random() * 2000 - 1000;
          particle.position.z = Math.random() * 2000 - 1000;
          particle.scale.x = particle.scale.y = 1;
          scene.add(particle);
          particles.push(particle)
        }
        container.appendChild(renderer.domElement);
        document.addEventListener("mousemove", onDocumentMouseMove, false);
        document.addEventListener("touchstart", onDocumentTouchStart, false);
        document.addEventListener("touchmove", onDocumentTouchMove, false);
        setInterval(loop, 1000 / 50)
      }
    複製程式碼
  • 倒數計時

    1.這個不用多說,給一個起初時間和當前時間對比,然後操作對應的dom元素,然後控制title

    countTime('2017/02/12 00:00', 'day', 'hour', 'minute', 'second');
    var days = parseInt($('#day').text());
    var years = new Date().getFullYear();
    var month = new Date().getMonth() + 1;
    var dateDay = new Date().getDate();
    複製程式碼
  • 圖片,描述文字的切換

    1.為了避免圖片過多同時載入緩慢問題--這裡js設定一個圖片列表和對應兩個圖片描述兩個變數,同時為了保證圖片載入出來才切換圖片描述文字,用到了img的load事件函式

    curImgDom.src = imgList[imgIndex];
      // curImgDom.setAttribute('src', imgList[imgIndex]);
      if (isInitImage) {
          $('.img-intro').text(imgDescList[imgIndex]);
          return;
      }else {
          // curImgDom.src = imgList[imgIndex];
          if (curImgDom.complete) {
              $('.img-intro').text(imgDescList[imgIndex]);
              return false;
          }
          curImgDom.onload = function () {
              $('.img-intro').text(imgDescList[imgIndex]);
          };
      }
    複製程式碼
  • 音訊播放

    1. 裡音訊設定自動,迴圈播放,點選圖示暫停,播放切換。這裡監聽了audio的play,canplaythrough(保證音訊載入完畢)事件,這裡值得注意一點是,audio的play()方法執行後返回來的promise物件,用來判斷是否成功執行(播放),可以根據這個promise控制音樂?圖示的旋轉or停止狀態,大致程式碼如下:
    audioDom.addEventListener('canplaythrough', function () {
          try {
              // chrome瀏覽器沒有也頁面互動(點選,滾動)之前會報錯誤---Uncaught(in promise)DOMException:play()
              //處理方法設定瀏覽器autoplay-policy---https://blog.csdn.net/super_XYQ/article/details/83026792
              var promise = audioDom.play();
              if (promise !== undefined) {
                  promise.then(function () {
                      musicCloseDom.classList.add('rotate');
                  }).catch(function () {
                      musicCloseDom.classList.remove('rotate');
                  });
              }
          } catch (error) {
              console.log('error', error);
          }
      }, false);
    複製程式碼
  • 設定Open graph(從瀏覽器分享到社交網路配置)

    如圖

    程式碼如下

    <!--從chrome分享到微信效果如上-->
    <meta property="og:type" content="website">
    <meta property="og:url" content="https://jackluson.github.io/to-lover-demo/">
    <meta property="og:description" content="一個記錄“我們在一起走過點點滴滴”的idea">
    <meta property="og:title" content="寶貝,感謝你一直的陪伴!">
    <meta property="og:image" content="https://jackluson.github.io/to-lover-demo/pic-icon.png">
    <meta property="og:image:width" content="140">
    <meta property="og:image:height" content="109">
    複製程式碼

其他(python輔助)

  1. 這裡用到了python指令碼生成藝術二維碼

    如圖

    version, level, qr_name = myqr.run(
    	'https://jackluson.github.io/to-lover-demo/',
    	# 'https://jackluson.github.io/to-lover/',
        version=1,
        level='H',
        picture='pic-icon.png',
        colorized=True,
        contrast=1.0,
        brightness=1.0,
        save_name='ip_jackLu.png',
        save_dir=os.getcwd()
    )
    複製程式碼
  2. 還有利用python壓縮圖片,與剪下音訊,避免檔案過大

    from glob import glob
    from PIL import Image
    import pyperclip
    source_dir = 'origin_images'
    target_dir = 'images'
    threshold = 1.5*1024*1024
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)
    filenames = glob('{}/*.[jp]*'.format(source_dir))
    # print(','.join(filenames))
    strFileNames = ''
    for i,filename  in enumerate(filenames):
      # 拼接檔名字串
      strFileNames = strFileNames +  '"' + filename +'",'
      filesize = os.path.getsize(filename)
      output_filename = filename.replace(source_dir, target_dir)
      # output_filename = time.strftime("%Y-%m-%d", time.localtime()) + '000' + str(i) + '.png';
    
      print('output_filename:',output_filename)
      if filesize >= threshold:
        print(filename)
        with Image.open(filename) as im:
          width, height = im.size
          new_width = width // 2
          new_height = int(new_width * height * 1.0 / width)
          print('adjusted size:', new_width, new_height)
          resized_im = im.resize((new_width, new_height))
          resized_im.save(output_filename)
      else:
        with Image.open(filename) as im:
          im.save(output_filename)
    
    # 字串複製到剪下板
    strFileNames = strFileNames.replace(source_dir + '\\', './' + target_dir + '/')
    print(strFileNames[0:-1]);
    pyperclip.copy(strFileNames[0:-1]);
    spam = pyperclip.paste()
    # 剪下音訊
    from pydub import AudioSegment
    file_name = "./media/zui-mei-qing-lv.mp3"
    sound = AudioSegment.from_mp3(file_name)
    start_time = "0:08"
    stop_time = "1:37"
    print ("time:",start_time,"~",stop_time)
    start_time = (int(start_time.split(':')[0])*60+int(start_time.split(':')[1]))*1000
    stop_time = (int(stop_time.split(':')[0])*60+int(stop_time.split(':')[1]))*1000
    print("ms:",start_time,"~",stop_time)
    word = sound[start_time:stop_time]
    # save_name = "xiaye-and-anlian.mp3-"+file_name[6:]
    save_name = "./media/zui-mei-qing-lv-cut.mp3"
    print (save_name)
    word.export(save_name, format="mp3",tags={'artist': 'AppLeU0', 'album': save_name[:-4]})
    複製程式碼

最後

其他不囉嗦了,專案地址github.com/jackluson/t… 有問題多謝能夠指出!

相關文章