介紹
基于畫布組件、動(dòng)畫樣式,實(shí)現(xiàn)的一個(gè)自定義抽獎(jiǎng)圓形轉(zhuǎn)盤。包含如下功能:
- 通過(guò)畫布組件canvas,畫出抽獎(jiǎng)圓形轉(zhuǎn)盤。
- 通過(guò)動(dòng)畫樣式設(shè)置動(dòng)畫,實(shí)現(xiàn)抽獎(jiǎng)功能。
- 通過(guò)自定義彈窗dialog彈出抽中的獎(jiǎng)品。
相關(guān)概念
- [stack組件]:堆疊容器,子組件按照順序依次入棧,后一個(gè)子組件覆蓋前一個(gè)子組件。
- [canvas組件]:畫布組件,用于自定義繪制圖形。
- [CanvasRenderingContext2D對(duì)象]:使用CanvasRenderingContext2D在canvas畫布組件上進(jìn)行繪制,繪制對(duì)象可以是矩形、文本、圖片等。
- [動(dòng)畫樣式]:組件支持動(dòng)態(tài)的旋轉(zhuǎn)、平移、縮放效果,可在style或css中設(shè)置。
- [自定義彈窗dialog]:自定義彈窗。
環(huán)境搭建
軟件要求
- [DevEco Studio]版本:DevEco Studio 3.1 Release及以上版本。
- OpenHarmony SDK版本:API version 9及以上版本。
硬件要求
- 開(kāi)發(fā)板類型:[潤(rùn)和RK3568開(kāi)發(fā)板]。
- OpenHarmony系統(tǒng):3.2 Release及以上版本。
環(huán)境搭建
完成本篇Codelab我們首先要完成開(kāi)發(fā)環(huán)境的搭建,本示例以RK3568開(kāi)發(fā)板為例,參照以下步驟進(jìn)行:
- [獲取OpenHarmony系統(tǒng)版本]:標(biāo)準(zhǔn)系統(tǒng)解決方案(二進(jìn)制)。以3.2 Release版本為例:
- 搭建燒錄環(huán)境。
- [完成DevEco Device Tool的安裝]
- [完成RK3568開(kāi)發(fā)板的燒錄](méi)
- 搭建開(kāi)發(fā)環(huán)境。
代碼結(jié)構(gòu)解讀
本篇Codelab只對(duì)核心代碼進(jìn)行講解,對(duì)于完整代碼,我們會(huì)在gitee中提供。
`HarmonyOS與OpenHarmony鴻蒙文檔籽料:mau123789是v直接拿`
├──entry/src/main/js // 代碼區(qū)
│ └──MainAbility
│ ├──common
│ │ ├──constants
│ │ │ ├──colorConstants.js // 顏色常量類
│ │ │ └──commonConstants.js // 公共常量類
│ │ ├──images // 圖片資源目錄
│ │ └──utils
│ │ └──logger.js // 日志工具類
│ ├──i18n
│ │ ├──en-US.json // 英文國(guó)際化
│ │ └──zh-CN.json // 中文國(guó)際化
│ ├──pages
│ │ └──index
│ │ ├──index.css // index頁(yè)面樣式
│ │ ├──index.hml // index頁(yè)面
│ │ └──index.js // index頁(yè)面邏輯
│ └──app.js // 程序入口
└──entry/src/main/resources // 應(yīng)用資源目錄
構(gòu)建主界面
在這個(gè)章節(jié)中,我們將完成示例主界面的開(kāi)發(fā),效果如圖所示:
在index.hml布局界面中添加畫布組件canvas,畫出抽獎(jiǎng)圓形轉(zhuǎn)盤,然后添加image組件,實(shí)現(xiàn)“開(kāi)始抽獎(jiǎng)”的布局。
< !-- index.hml -- >
< stack class="container" >
< canvas ref="canvas" class="canvas-box simple-animation" ... >< /canvas >
< image id="center" src="/common/images/ic_center.png" ... >< /image >
...
< /stack >
在繪制抽獎(jiǎng)圓形轉(zhuǎn)盤前,首先需要在index.js的onInit()方法中獲取當(dāng)前設(shè)備的屏幕密度和屏幕的寬高。
// index.js
import resourceManager from '@ohos.resourceManager';
import featureAbility from '@ohos.ability.featureAbility';
// 頁(yè)面初始化時(shí)觸發(fā)
onInit() {
// 獲取當(dāng)前設(shè)備的屏幕密度
resourceManager.getResourceManager((error, mgr) = > {
if(error) {
Logger.error(`[index][onInit]getResourceManager error is ${JSON.stringify(error)}`);
return;
}
mgr.getDeviceCapability().then(value = > {
let screenDensity = value.screenDensity;
// 獲取屏幕的大小,不包含狀態(tài)欄大小
featureAbility.getWindow().then((data) = > {
let windowProperties = data.getWindowProperties();
this.screenWidth = windowProperties.windowRect.width / screenDensity;
this.screenHeight = windowProperties.windowRect.height / screenDensity;
});
}).catch(err = > {
Logger.error(`[index][onInit]getDeviceCapability error is ${JSON.stringify(err)}`);
});
});
}
在index.js的onShow()方法中,獲取CanvasRenderingContext2D對(duì)象,用于在畫布組件上繪制矩形、文本、圖片等。然后通過(guò)draw()方法逐步繪制自定義抽獎(jiǎng)圓形轉(zhuǎn)盤。
// index.js
// 頁(yè)面顯示時(shí)觸發(fā)
onShow() {
if (this.ctx !== null) {
return;
}
// 獲取CanvasRenderingContext2D對(duì)象
this.ctx = this.$refs.canvas.getContext('2d');
this.avgAngle = CommonConstants.CIRCLE / CommonConstants.COUNT;
this.draw();
}
// 畫抽獎(jiǎng)圓形轉(zhuǎn)盤
draw() {
// 將畫布沿X、Y軸平移指定距離
this.ctx.translate(this.screenWidth / CommonConstants.HALF,
this.screenHeight / CommonConstants.HALF);
// 畫外部圓盤的花瓣
this.drawFlower();
// 畫外部圓盤、小圈圈
this.drawOutCircle();
// 畫內(nèi)部圓盤
this.drawInnerCircle();
// 畫內(nèi)部扇形抽獎(jiǎng)區(qū)域
this.drawInnerArc();
// 畫內(nèi)部扇形區(qū)域文字
this.drawArcText();
// 畫內(nèi)部扇形區(qū)域獎(jiǎng)品對(duì)應(yīng)的圖片
this.drawImage();
}
畫外部圓盤
畫外部圓盤的花瓣:通過(guò)調(diào)用rotate()方法,將畫布旋轉(zhuǎn)指定角度。再通過(guò)調(diào)用save()和restore()方法,使畫布保存最新的繪制狀態(tài)。根據(jù)想要繪制的花瓣個(gè)數(shù),改變旋轉(zhuǎn)角度,循環(huán)畫出花瓣效果。
// index.js
// 畫外部圓盤的花瓣
drawFlower() {
let beginAngle = this.startAngle + this.avgAngle;
const pointY = this.screenWidth * CommonConstants.FLOWER_POINT_Y_RATIOS;
const radius = this.screenWidth * CommonConstants.FLOWER_RADIUS_RATIOS;
const innerRadius = this.screenWidth * CommonConstants.FLOWER_INNER_RATIOS;
for (let i = 0; i < CommonConstants.COUNT; i++) {
this.ctx.save();
this.ctx.rotate(beginAngle * Math.PI / CommonConstants.HALF_CIRCLE);
this.ctx.beginPath();
this.ctx.fillStyle = ColorConstants.FLOWER_OUT_COLOR;
this.ctx.arc(0, -pointY, radius, 0, Math.PI * CommonConstants.HALF);
this.ctx.fill();
this.ctx.beginPath();
this.ctx.fillStyle = ColorConstants.FLOWER_INNER_COLOR;
this.ctx.arc(0, -pointY, innerRadius, 0, Math.PI * CommonConstants.HALF);
this.ctx.fill();
beginAngle += this.avgAngle;
this.ctx.restore();
}
}
畫外部圓盤、圓盤邊上的小圈圈:在指定的X、Y(0, 0)坐標(biāo)處,畫一個(gè)半徑為this.screenWidth * CommonConstants.OUT_CIRCLE_RATIOS的圓形。接下來(lái)通過(guò)一個(gè)for循環(huán),且角度每次遞增CommonConstants.CIRCLE / CommonConstants.SMALL_CIRCLE_COUNT,來(lái)繪制圓環(huán)上的小圈圈。
// index.js
// 畫外部圓盤、小圈圈
drawOutCircle() {
// 畫外部圓盤
this.ctx.beginPath();
this.ctx.fillStyle = ColorConstants.OUT_CIRCLE_COLOR;
this.ctx.arc(0, 0, this.screenWidth * CommonConstants.OUT_CIRCLE_RATIOS, 0, Math.PI * CommonConstants.HALF);
this.ctx.fill();
// 畫小圓圈
let beginAngle = this.startAngle;
for (let i = 0; i < CommonConstants.SMALL_CIRCLE_COUNT; i++) {
this.ctx.save();
this.ctx.rotate(beginAngle * Math.PI / CommonConstants.HALF_CIRCLE);
this.ctx.beginPath();
this.ctx.fillStyle = ColorConstants.WHITE_COLOR;
this.ctx.arc(this.screenWidth * CommonConstants.SMALL_CIRCLE_RATIOS, 0,
CommonConstants.SMALL_CIRCLE_RADIUS, 0, Math.PI * CommonConstants.HALF);
this.ctx.fill();
beginAngle = beginAngle + CommonConstants.CIRCLE / CommonConstants.SMALL_CIRCLE_COUNT;
this.ctx.restore();
}
}
畫內(nèi)部扇形抽獎(jiǎng)區(qū)域
畫內(nèi)部圓盤、內(nèi)部扇形抽獎(jiǎng)區(qū)域:使用canvas的arc()方法繪制內(nèi)部圓盤。通過(guò)一個(gè)for循環(huán),角度每次遞增this.avgAngle。然后不斷更改弧線的起始弧度this.startAngle * Math.PI / CommonConstants.HALF_CIRCLE和弧線的終止弧度(this.startAngle + this.avgAngle) * Math.PI / CommonConstants.HALF_CIRCLE。最后用fill()方法對(duì)路徑進(jìn)行填充。
// index.js
// 畫內(nèi)部圓盤
drawInnerCircle() {
this.ctx.beginPath();
this.ctx.fillStyle = ColorConstants.INNER_CIRCLE_COLOR;
this.ctx.arc(0, 0, this.screenWidth * CommonConstants.INNER_CIRCLE_RATIOS, 0, Math.PI * CommonConstants.HALF);
this.ctx.fill();
this.ctx.beginPath();
this.ctx.fillStyle = ColorConstants.WHITE_COLOR;
this.ctx.arc(0, 0, this.screenWidth * CommonConstants.INNER_WHITE_CIRCLE_RATIOS, 0, Math.PI * CommonConstants.HALF);
this.ctx.fill();
},
// 畫內(nèi)部扇形抽獎(jiǎng)區(qū)域
drawInnerArc() {
let colors = [
ColorConstants.ARC_PINK_COLOR, ColorConstants.ARC_YELLOW_COLOR,
ColorConstants.ARC_GREEN_COLOR, ColorConstants.ARC_PINK_COLOR,
ColorConstants.ARC_YELLOW_COLOR, ColorConstants.ARC_GREEN_COLOR
];
let radius = this.screenWidth * CommonConstants.INNER_ARC_RATIOS;
for (let i = 0; i < CommonConstants.COUNT; i++) {
this.ctx.beginPath();
this.ctx.fillStyle = colors[i];
this.ctx.arc(0, 0, radius, this.startAngle * Math.PI / CommonConstants.HALF_CIRCLE,
(this.startAngle + this.avgAngle) * Math.PI / CommonConstants.HALF_CIRCLE);
this.ctx.fill();
this.ctx.lineTo(0, 0);
this.ctx.fill();
this.startAngle += this.avgAngle;
}
}
畫內(nèi)部抽獎(jiǎng)區(qū)域文字:用for循環(huán),通過(guò)drawCircularText()方法繪制每組文字。drawCircularText()方法接收三個(gè)參數(shù),分別是字符串、起始弧度和終止弧度。繪制文本前需要設(shè)置每個(gè)字母占的弧度angleDecrement,然后設(shè)置水平和垂直的偏移量。垂直偏移量circleText.y - Math.sin(angle) * radius就是朝著圓心移動(dòng)的距離;水平偏移circleText.x + Math.cos(angle) * radius,是為了讓文字在當(dāng)前弧范圍文字居中。最后使用fillText()方法繪制文本。
// index.js
// 畫內(nèi)部扇形區(qū)域文字
drawArcText() {
this.ctx.textAlign = CommonConstants.TEXT_ALIGN;
this.ctx.textBaseline = CommonConstants.TEXT_BASE_LINE;
this.ctx.fillStyle = ColorConstants.TEXT_COLOR;
this.ctx.font = CommonConstants.CANVAS_FONT;
let textArrays = [
this.$t('strings.text_smile'),
this.$t('strings.text_hamburger'),
this.$t('strings.text_cake'),
this.$t('strings.text_smile'),
this.$t('strings.text_beer'),
this.$t('strings.text_watermelon')
];
let arcTextStartAngle = CommonConstants.ARC_START_ANGLE;
let arcTextEndAngle = CommonConstants.ARC_END_ANGLE;
for (let i = 0; i < CommonConstants.COUNT; i++) {
this.drawCircularText(textArrays[i],
(this.startAngle + arcTextStartAngle) * Math.PI / CommonConstants.HALF_CIRCLE,
(this.startAngle + arcTextEndAngle) * Math.PI / CommonConstants.HALF_CIRCLE);
this.startAngle += this.avgAngle;
}
},
// 繪制圓弧文本
drawCircularText(textString, startAngle, endAngle) {
let circleText = {
x: 0,
y: 0,
radius: this.screenWidth * CommonConstants.INNER_ARC_RATIOS
};
// 圓的半徑
let radius = circleText.radius - circleText.radius / CommonConstants.COUNT;
// 每個(gè)字母占的弧度
let angleDecrement = (startAngle - endAngle) / (textString.length - 1);
let angle = startAngle;
let index = 0;
let character;
while (index < textString.length) {
character = textString.charAt(index);
this.ctx.save();
this.ctx.beginPath();
this.ctx.translate(circleText.x + Math.cos(angle) * radius,
circleText.y - Math.sin(angle) * radius);
this.ctx.rotate(Math.PI / CommonConstants.HALF - angle);
this.ctx.fillText(character, 0, 0);
angle -= angleDecrement;
index++;
this.ctx.restore();
}
}
畫內(nèi)部抽獎(jiǎng)區(qū)域文字對(duì)應(yīng)圖片:使用canvas的drawImage()方法繪制抽獎(jiǎng)區(qū)域文字對(duì)應(yīng)圖片,該方法接收五個(gè)參數(shù),分別是圖片資源、繪制區(qū)域左上角的X和Y軸坐標(biāo)、繪制區(qū)域的寬度和高度。
// index.js
// 畫內(nèi)部扇形區(qū)域獎(jiǎng)品對(duì)應(yīng)的圖片
drawImage() {
let beginAngle = this.startAngle;
let imageSrc = [
CommonConstants.WATERMELON_IMAGE_URL, CommonConstants.BEER_IMAGE_URL,
CommonConstants.SMILE_IMAGE_URL, CommonConstants.CAKE_IMAGE_URL,
CommonConstants.HAMBURG_IMAGE_URL, CommonConstants.SMILE_IMAGE_URL
];
let image = new Image();
for (let i = 0; i < CommonConstants.COUNT; i++) {
image.src = imageSrc[i];
this.ctx.save();
this.ctx.beginPath();
this.ctx.rotate(beginAngle * Math.PI / CommonConstants.HALF_CIRCLE);
this.ctx.drawImage(image, this.screenWidth * CommonConstants.IMAGE_DX_RATIOS,
this.screenWidth * CommonConstants.IMAGE_DY_RATIOS, CommonConstants.IMAGE_SIZE,
CommonConstants.IMAGE_SIZE);
beginAngle += this.avgAngle;
this.ctx.restore();
}
}
實(shí)現(xiàn)抽獎(jiǎng)功能
在index.hml的canvas組件中添加動(dòng)畫樣式的屬性,在image組件中添加點(diǎn)擊事件onclick。點(diǎn)擊“開(kāi)始抽獎(jiǎng)”圖片,圓形轉(zhuǎn)盤開(kāi)始轉(zhuǎn)動(dòng)抽獎(jiǎng)。
< !-- index.hml -- >
< stack class="container" >
< canvas ref="canvas" class="canvas-box simple-animation"
style="transform: rotate({{ rotateDegree }}); animation-iteration-count: {{ infinite }};
animation-play-state: {{ playState }};" >
< /canvas >
< image id="center" src="/common/images/ic_center.png"
onclick="startAnimator" disabled="{{ disabledFlag }}" >
< /image >
...
< /stack >
在index.css中設(shè)置相應(yīng)的動(dòng)畫樣式,使圓形轉(zhuǎn)盤可以通過(guò)動(dòng)畫轉(zhuǎn)動(dòng)抽獎(jiǎng)。
/* index.css */
.simple-animation {
animation-name: luckyCircle;
animation-duration: 4s;
animation-delay: 0s;
animation-timing-function: ease;
}
@keyframes luckyCircle {
from {
transform: rotate(0deg);
}
to {
transform: rotate(1800deg);
}
}
圓形轉(zhuǎn)盤開(kāi)始轉(zhuǎn)動(dòng)抽獎(jiǎng):給轉(zhuǎn)盤指定一個(gè)隨機(jī)的轉(zhuǎn)動(dòng)角度randomAngle,保證每次轉(zhuǎn)動(dòng)的角度是隨機(jī)的,即每次抽到的獎(jiǎng)品也是隨機(jī)的。動(dòng)畫結(jié)束后,轉(zhuǎn)盤停止轉(zhuǎn)動(dòng),抽獎(jiǎng)結(jié)束,彈出抽中的獎(jiǎng)品信息。
// index.js
// 開(kāi)始抽獎(jiǎng)
startAnimator() {
this.disabledFlag = !this.disabledFlag;
let randomAngle = Math.round(Math.random() * CommonConstants.CIRCLE);
// 獲取中獎(jiǎng)信息
this.showPrizeData(randomAngle);
if (this.infinite === 0) {
// 永久旋轉(zhuǎn)
this.infinite = -1;
}
setTimeout(() = > {
this.infinite = 0;
this.playState = CommonConstants.PLAY_STATE.pause;
// 打開(kāi)自定義彈窗,彈出獎(jiǎng)品信息
this.$element('prize-dialog').show();
}, CommonConstants.DURATION);
this.rotateDegree = CommonConstants.CIRCLE * CommonConstants.FIVE_CIRCLE +
CommonConstants.ANGLE - randomAngle;
this.playState = CommonConstants.PLAY_STATE.running;
}
彈出抽中的獎(jiǎng)品信息:抽獎(jiǎng)結(jié)束后,彈出抽中的圖片和文本信息,通過(guò)自定義彈窗dialog實(shí)現(xiàn)。
< !-- index.hml -- >
< stack class="container" >
...
< dialog id="prize-dialog" oncancel="closeDialog" >
< div class="dialog-div" >
< image id="prize-image" src="{{ prizeData.imageSrc }}" >< /image >
< text class="txt message" >{{ prizeData.message }}< /text >
< text class="txt confirm" onclick="closeDialog" >{{ $t('strings.confirm_text') }}< /text >
< /div >
< /dialog >
< /stack >
點(diǎn)擊自定義彈窗的確定按鈕,關(guān)閉彈窗。
// index.js
// 關(guān)閉自定義彈窗
closeDialog() {
this.$element('prize-dialog').close();
this.disabledFlag = !this.disabledFlag;
}
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
57文章
2410瀏覽量
43301 -
HarmonyOS
+關(guān)注
關(guān)注
79文章
1987瀏覽量
31102 -
OpenHarmony
+關(guān)注
關(guān)注
25文章
3770瀏覽量
17046
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
HarmonyOS開(kāi)發(fā)案例:【W(wǎng)eb組件實(shí)現(xiàn)抽獎(jiǎng)】

HarmonyOS開(kāi)發(fā)案例:【抽獎(jiǎng)轉(zhuǎn)盤】

Deyisupport 社區(qū) 6 周年慶 —— 三重活動(dòng) + 幸運(yùn)大轉(zhuǎn)盤抽獎(jiǎng)
HarmonyOS IoT 硬件開(kāi)發(fā)案例分享
【潤(rùn)和直播課預(yù)告@華為開(kāi)發(fā)者學(xué)院】HarmonyOS設(shè)備開(kāi)發(fā)基礎(chǔ)課程|HiSpark WiFi-IoT 智能小車套件開(kāi)發(fā)案例
6月2日!華為HarmonyOS2.0發(fā)布會(huì)直播間抽獎(jiǎng)公示&領(lǐng)獎(jiǎng)方式
通過(guò)一個(gè)圓形抽獎(jiǎng)轉(zhuǎn)盤演示HarmonyOS自定義組件的實(shí)現(xiàn)
聲光電子轉(zhuǎn)盤聲光電子轉(zhuǎn)盤的電路原理圖

許思維老師HarmonyOS IoT硬件開(kāi)發(fā)案例分享

華為開(kāi)發(fā)者分論壇HarmonyOS學(xué)生公開(kāi)課-OpenHarmony Codelabs開(kāi)發(fā)案例

基于SpringBoot+Redis的轉(zhuǎn)盤抽獎(jiǎng)

評(píng)論