- Vue.js 2 Web Development Projects
- Guillaume Chau
- 258字
- 2021-07-02 22:34:37
The animated clouds
To add some life to the game world, we will create a few clouds that will slide in the sky. Their position and animation duration will be random and they will go from the left to the right of the window.
- In the world.js file, add the minimum and maximum durations for the cloud animation:
const cloudAnimationDurations = {
min: 10000, // 10 sec
max: 50000, // 50 sec
}
- Then, create the cloud component with an image and a type prop:
Vue.component('cloud', {
template: `<p class="cloud" :class="'cloud-' + type" >
<img :src="'svg/cloud' + type + '.svg'" />
</p>`,
props: ['type'],
})
There will be five different clouds, so the type prop will range from 1 to 5.
- We will need to change the z-index and transform CSS properties of the component with a reactive style data property:
data () {
return {
style: {
transform: 'none',
zIndex: 0,
},
}
},
- Apply these style properties with the v-bind directive:
<p class="cloud" :class="'cloud-' + type" :style="style">
- Let's create a method to set the position of the cloud component using the transform CSS property:
methods: {
setPosition (left, top) {
// Use transform for better performance
this.style.transform = `translate(${left}px, ${top}px)`
},
}
- We need to initialize the horizontal position of the cloud when the image is loaded, so that it's outside of the viewport. Create a new initPosition that uses the setPosition method:
methods: {
// ...
initPosition () {
// Element width
const width = this.$el.clientWidth
this.setPosition(-width, 0)
},
}
- Add an event listener on the image with the v-on directive shorthand that listens to the load event and calls the initPosition method:
<img :src="'svg/cloud' + type + '.svg'" @load="initPosition" />
推薦閱讀
- Python從菜鳥到高手(第2版)
- Python程序設(shè)計(第3版)
- Visual FoxPro 程序設(shè)計
- 信息安全技術(shù)
- Angular開發(fā)入門與實戰(zhàn)
- Mastering Business Intelligence with MicroStrategy
- C++反匯編與逆向分析技術(shù)揭秘(第2版)
- Java Web從入門到精通(第3版)
- Android嵌入式系統(tǒng)程序開發(fā):基于Cortex-A8(第2版)
- Getting Started with Polymer
- Python函數(shù)式編程(第2版)
- Android應(yīng)用程序設(shè)計
- Backbone.js Patterns and Best Practices
- JavaScript程序設(shè)計基礎(chǔ)教程(慕課版)
- 新手學(xué)ASP動態(tài)網(wǎng)頁開發(fā)