DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5教程
用 HTML5 Canvas 做一個圓盤抽獎轉盤
編輯:HTML5教程     

抽獎轉盤是活動頁面最常見的互動元素之一。它的運作原理和先前的 jQuery 版本一樣:先由亂數決定結果,再把轉盤旋轉到對應角度停下,讓視覺去「配合」已經定好的答案。改用 Canvas 實作的好處是繪製完全可控,扇形、文字、圖示都能自己畫,不必依賴圖片切圖。

體驗效果:https://hovertree.com/texiao/html5/14/

結構設計

畫面用多層 canvas 疊出景深:底層畫轉盤本體,中層放轉盤以外的裝飾與文字,最上層是中央的指針與按鈕。多層分開繪製的用意是旋轉時只需重畫會動的那一層,效能明顯更好。

<div class="turnplate_box">
  <canvas id="myCanvas" width="300" height="300">瀏覽器不支援。</canvas>
  <canvas id="myCanvas01" width="200" height="200">瀏覽器不支援。</canvas>
  <canvas id="myCanvas03" width="200" height="200">瀏覽器不支援。</canvas>
  <canvas id="myCanvas02" width="150" height="150">瀏覽器不支援。</canvas>
  <button id="tupBtnHovertree" class="turnplatw_btn"></button>
</div>

頁面同時引入 main.css 與 main.js,前者負責版面與按鈕外觀,後者負責繪製與旋轉動畫;<meta name="viewport"> 則確保手機上不會縮放錯亂。

把系統 alert 換成自訂彈窗

原生的 alert() 在抽獎結果出現時相當突兀,無法客製、會阻塞執行緒。範例直接覆寫 window.alert,改成插入一組自繪的遮罩與提示框,並提供關閉函式:

window.alert = function (str) {
  var shield = document.createElement("DIV");
  shield.id = "shield";
  shield.style.cssText = "position:absolute;left:50%;top:50%;width:280px;height:150px;" +
    "margin-left:-140px;margin-top:-110px;z-index:25";
  var alertFram = document.createElement("DIV");
  alertFram.id = "alertFram";
  alertFram.style.cssText = "position:absolute;left:50%;top:50%;width:280px;height:150px;" +
    "margin-left:-140px;margin-top:-110px;text-align:center;line-height:150px;z-index:300";
  // 組出標題列、內容列與確定鈕後插入 body
  alertFram.innerHTML = strHtml;
  document.body.appendChild(alertFram);
  document.body.appendChild(shield);
  this.doOk = function () {
    alertFram.style.display = "none";
    shield.style.display = "none";
  };
  alertFram.focus();
  document.body.onselectstart = function () { return false; };
}

實作要點

幾個容易忽略的細節:旋轉角度要用「緩減」曲線收尾,轉太快或瞬間停止都會讓人覺得假的;停下時的角度必須精準對齊扇形中心線,否則指針會壓在分界上;另外,抽獎結果務必在後端產生並校驗,前端只負責呈現,避免有人改 JS 直接拿到大獎。

相關題目:https://hovertree.com/shortanswer/bjae/dmjcxkns.htm

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved