本代码为小白本人原创,转载请标明出处
创作灵感:https://www.kkkk1000.com/images/learnPixiJS-VisualEffects/AnimatedMask.html
大家可以看下他的源码
效果图:因为制作gif图就用了五张,实际效果肯定是连贯自然的
写的不好各位大神可以提点宝贵意见,本着无坑快速易懂的原则,代码我都一一注释,放心使用
----------------------------------------------------✂-------正文分割线----------------------------------------------------
需求:因为做的是天气系统,需要实现在地图对应的点添加雷暴、降水图形实现如上效果,百度了半天,踩了半天坑都是好几年前写的(是PIXi不火吗?),有用PIXI的shader着色器,有官网游戏代码生命条原理的,有用beginFill的,最后发现了PIXi的遮罩功能,通过遮罩可以简单快捷的实现该功能,但是还是有缺点的,具体缺点看完代码你就会发现
原理:1、在画布上创建两个纹理图像加载,一个是内部没填充颜色的,一个是有颜色的
2、绘制一个矩形作为有颜色的遮罩
3、通过requestAnimationFrame更新游戏状态,不断地升高遮罩的y值来试下效果(其实我感觉既然用了PIXI还是最好用PIXI自带的TICKER,单纯个人建议,我这里是写的demo顺手用了requestAnimationFrame,公司项目肯定正规用ticker)
深入理解定时器系列第二篇——被誉为神器的requestAnimationFrame - 小火柴的蓝色理想 - 博客园
上代码:
<template>
<div id="px" />
</template>
<script>
import * as PIXI from 'pixi.js'
export default {
name: 'Eee',
components: {},
data() {
return {
}
},
computed: {
},
watch: {
},
created() {
},
mounted() {
this.init()
},
methods: {
init() {
// 画布配置
const option = {
width: 640,
height: 360,
transparent: true// 这里控制画布是否透明
}
const shandian = require('../../assets/shandian.png')
const shandian1 = require('../../assets/shandian1.png')
// 创建一个 Pixi应用
const app = new PIXI.Application(option)
// 获取舞台
const stage = app.stage
// 获取渲染器
const renderer = app.renderer
const playground = document.getElementById('px')// 注意自己的id是什么
// 把 Pixi 创建的 canvas 添加到页面上
playground.appendChild(renderer.view)
// 需要用到的精灵
let shandianSprite
let shandian1Sprite
let clear
// 加载纹理
app.loader.add([shandian, shandian1]).load(setup)
function setup() {
const resources = app.loader.resources
shandianSprite = new PIXI.Sprite(resources[shandian].texture) // 这是红色的闪电图
shandian1Sprite = new PIXI.Sprite(resources[shandian1].texture)// 这是基本的闪电图
// 绘制矩形遮罩
clear = new PIXI.Graphics()
shandianSprite.mask = clear
clear.beginFill(0x66CCFF)
clear.drawRect(0, 0, 200, 200)
clear.endFill()
// 把精灵添加到舞台上
// console.log(shandian1Sprite.x)
stage.addChild(shandianSprite)
stage.addChild(shandian1Sprite)
stage.addChild(clear)
// 开始游戏循环
gameLoop()
// 将游戏的当前状态设置为play:
function gameLoop() {
const state = play
// 循环调用gameLoop
requestAnimationFrame(gameLoop)
// 更新当前的游戏状态
state()
// 渲染舞台
renderer.render(stage)
}
// 使遮罩移动的函数
function play() {
if (clear.y < 200) {
clear.y += 1
} else {
clear.y = 0
}
}
}
}
}
}
</script>
<style lang="scss" scoped>
</style>