微信小程序需要wxml,wxss,js三种类型代码
1,wxml
<view class="container"><view class="title">兔年头像生成器</view><view class="description">选择一张图片,生成你的兔年头像吧!</view><image class="avatar" src="{{avatarUrl}}"></image><button class="btn" bindtap="onButtonClick">生成头像</button><view class="result" wx:if="{{result}}">{{result}}</view>
</view>
2,wxss
.container {display: flex;flex-direction: column;align-items: center;justify-content: center;height: 100vh;}.title {font-size: 24px;font-weight: bold;margin-bottom: 20px;}.description {font-size: 18px;color: #666;margin-bottom: 30px;}.avatar {width: 200px;height: 200px;margin-bottom: 30px;}.btn {width: 200px;height: 40px;background-color: #007aff;color: #fff;border-radius: 20px;}.result {margin-top: 30px;font-size: 18px;color: #f00;}
3,js
Page({data: {avatarUrl: '/images/default-avatar.jpg',result: ''},onButtonClick: function() {wx.chooseImage({count: 1,success: res => {const tempFilePath = res.tempFilePaths[0];wx.getImageInfo({src: tempFilePath,success: res => {wx.showLoading({title: '头像生成中',});const ctx = wx.createCanvasContext('canvas');ctx.drawImage(res.path, 0, 0, 400, 400);const rabbitImage = '/images/rabbit.png';ctx.drawImage(rabbitImage, 250, 0, 150, 150);const rabbitEarsImage = '/images/rabbit-ears.png';ctx.drawImage(rabbitEarsImage, 230, -20, 200, 200);const rabbitNoseImage = '/images/rabbit-nose.png';ctx.drawImage(rabbitNoseImage, 280, 120, 100, 100);ctx.draw(false, () => {wx.canvasToTempFilePath({canvasId: 'canvas',success: res => {this.setData({avatarUrl: res.tempFilePath,result: '头像已生成!'});wx.hideLoading(); // 隐藏加载动画},fail: err => {console.error(err);wx.hideLoading(); // 隐藏加载动画}});});},fail: err => {console.error(err);}});},fail: err => {console.error(err);}});}})