uniapp vue2微信小程序使用wxml-to-canvas

Uniapp实战:5分钟搞定wxml-to-canvas动态页面转图片(附完整代码) 本文深入探讨了在Uniapp中使用wxml-to-canvas组件将动态页面高效转换为图片的实战方案。文章不仅提供了完整的代码示例,还详细解析了其核心原理、高级配置、性能优化策略以及常见问题的解决方案,旨在帮助开发者超越基础使用,实现复杂场景下的高性能图片生成。 阅读详情
AI摘要

博客介绍了uni-app和微信小程序的插件配置过程,包括下载依赖、创建文件夹、修改文件引用、全局插件引入等。还提及在页面模板中写入、封装mixin混入和notification.js等操作,同时指出使用时需注意样式问题及元素布局规则。

先下载依赖 

npm install --save wxml-to-canvas

下好后在node_modules中找到,创建一个wxcomponents文件夹,将这两个文件放进去。

将module.exports = require("widget-ui“);改为module.exports = require("../../widget-ui/dist/index.js");

然后在全局插件引入

"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "啊实打实的",
		"navigationBarBackgroundColor": "#fff5ff",
		"backgroundColor": "#F8F8F8",
		"usingComponents": {
			"wxml-to-canvas": "/wxcomponents/wxml-to-canvas/src/index"
		}
	},

ok 配置完成,接下来是在页面模板中写入

<wxml-to-canvas class="widget"></wxml-to-canvas>

然后封装mixin混入

// myMixin.js
const {
    wxml,
    style
} = require('./notification.js')
export default {
    data() {
        return {
            canvasWidth: 320, // 默认canvas宽高
            canvasHeight: 480,
            canvasScreenWidth: null, // 设备宽度
            canvasScreenHeight: null, // 设备宽度
            canvasControlContent: undefined,
            //上个页面用到的图片地址
            canvasTempFile: undefined
        }
    },
    methods: {
        async loadFun() {
            // 获取设备信息
            await wx.getSystemInfo({
                success: (res) => {
                    console.log('res.canvasScreenWidth', res);
                    this.canvasScreenWidth = res.screenWidth
                    this.canvasScreenHeight = 800 //高度建议计算得出或写死。如使用res.screenHeight,文字过长时无法生成(安卓手机,最新鸿蒙系统高度不能超过1000)
                    this.canvasWidth = this.canvasScreenWidth
                    this.canvasHeight = this.canvasScreenHeight
                    setTimeout(() => {
                        console.log('this', this);
                        console.log("this.selectComponent('.widget')", this.selectComponent('.widget'));
                        this.widget = this.selectComponent('.widget');
                        this.canvasControlContent = '你好呀';
                        this.canvasTempFile = 'https://img0.baidu.com/it/u=1715545265,2854041546&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=234'
                        this.download();
                    }, 1000)
                }
            });
        },
        //生成图片
        download() {
            // 数字容器宽度 动态设置 
            setTimeout(() => {
                uni.showLoading({
                    title: '图片生成中...'
                })
                this.renderToCanvas()
            }, 1000)
        },
        renderToCanvas() {
            const _wxml = wxml(this.chosen_chat_list) //调用wxml
            console.log('_wxml', _wxml);
            const _style = style(this.canvasScreenWidth, this.canvasWidth, this.canvasHeight)
            setTimeout(() => {
                console.log('this.widget', this.widget);
                const p1 = this.widget.renderToCanvas({
                    wxml: _wxml,
                    style: _style
                })
                p1.then((res) => {
                    console.log('生成成功', res);
                    uni.hideLoading()
                    this.saveImageToPhotosAlbum();
                }).catch((err) => {
                    console.log('生成失败')
                })
            }, 100)

        },
        //保存图片到本地
        saveImageToPhotosAlbum() {
            uni.showLoading({
                title: '正在保存中...'
            })
            const p2 = this.widget.canvasToTempFilePath()
            console.log('p2', p2);
            let that = this
            p2.then(result => {
                let path = result.tempFilePath
                console.log('path', path);
                uni.saveImageToPhotosAlbum({
                    filePath: path,
                    success: () => {
                        uni.hideLoading()
                        uni.showToast({
                            title: '保存成功,可去手机相册查看',
                            duration: 2000,
                            icon: 'none'
                        });
                        uni.navigateBack();
                    }
                });
            })
        }
    }
}
let aaa = {
    data() {
        return {
            canvasW: 0, // 画布宽
            canvasH: 0, // 画布高
            canvasSystemInfo: {}, // 设备信息
            canvasGoodsImg: {}, // 商品主图信息
            canvasEwmW: 140, // 二维码大小
            canvasTitle: '商品标题商品标题商品标题', // 商品标题
            canvasPrice: '4158.00', // 价格
            canvasName: '浪迹天涯', // 推荐人
            canvasIsShow: false,
            domContent: `
            <div id="source-element">
              <h1 style="color: blue; text-align: center;">这是一个标题</h1>
            </div>
          `,
        };
    },
    methods: {
        async loadFun() {
            // 获取设备信息,主要获取宽度,赋值给canvasW 也就是宽度:100%
            this.canvasSystemInfo = await this.getSystemInfo();
            console.log(this.canvasSystemInfo, '我是设备宽度');
            this.canvasTitle = '我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题我是标题';
            this.canvasPrice = '价格价格价格';
            // 获取主图,二维码信息
            // let goodsImgUrl = option.goosImg // 主图本地路径,也可以用网络地址
            let goodsImgUrl = 'http://img.touxiangwu.com/2020/3/uq6Bja.jpg' // 头部封面图片
            // shareCodeGet(param).then(res => {	//调接口
            // 	console.log(res, 'resres')
            // let ewmImgUrl = res.data.msg;	//二维码图片地址-从接口取
            // 以下内容放接口里面---下面的内容放接口里面-主要返回二维码地址
            // })
            let that = this
            uni.downloadFile({
                url: goodsImgUrl,
                success: async function (logoRes) {
                    goodsImgUrl = logoRes.tempFilePath
                    var ewmImgUrl = require('@/static/AIFlower.png')
                    // uni.downloadFile({
                    // url: ewmImgUrl,
                    // success: function (logoRes) {
                    // ewmImgUrl = logoRes.tempFilePath
                    that.canvasW = that.canvasSystemInfo.windowWidth; // 画布宽度
                    // 画布高度 = 主图高度+二维码高度 + 文字图片的间距(大概50)
                    that.canvasH = 580 //this.canvasGoodsImg.height + this.canvasEwmW + 10;  
                    uni.showToast({
                        icon: 'loading',
                        mask: true,
                        duration: 10000,
                        title: '海报绘制中',
                    });
                    setTimeout(() => {
                        var ctx = uni.createCanvasContext('myCanvas', that);

                        //列表部分
                        var fontSize = 12;
                        var itemHeight = fontSize + 5;
                        var x = 5;
                        var y = fontSize;

                        ctx.font = fontSize + "px Arial";
                        console.log(' this.chosen_chat_list', that.chosen_chat_list);
                        that.chosen_chat_list.forEach(item => {
                            // 绘制列表项
                            ctx.fillText(item.content, x, y);
                            // 移动到下一个位置
                            y += itemHeight;
                        });
                        //底部
                        ctx.setFontSize(14)
                        ctx.setFillStyle('#b8b8b8')
                        ctx.fillText(
                            '长按或扫描识别二维码' || '', that.canvasW / 2 - that.canvasW / 2.4 / 2,
                            that.canvasW + that.canvasEwmW + 10);

                        // draw方法 把以上内容画到 canvas 中
                        ctx.draw(true, (ret) => {
                            that.canvasIsShow = true // 显示按钮-保存图片到相册
                            uni.showToast({
                                icon: 'success',
                                mask: true,
                                title: '绘制完成',
                            });
                            uni.canvasToTempFilePath({ // 保存canvas为图片
                                canvasId: 'myCanvas',
                                quality: 1,
                                complete: function (res) {
                                    // 在H5平台下,tempFilePath 为 base64, // 图片提示跨域 H5保存base64失败,APP端正常输出临时路径
                                    console.log(res.tempFilePath, '66666666')
                                    // uni.setStorageSync('filePath', res.tempFilePath) //保存临时文件路径到缓存
                                },
                            })
                        });
                    }, 1500)

                    // },
                    // fail:(err)=>{
                    //     console.log('图片下载失败',err);
                    // }
                    // })
                }
            })
        },
        async drawDomToCanvas() {
            // 创建一个不可见的容器并插入DOM内容
            const hiddenContainer = document.getElementById("hidden-container");
            this.domContent = `<view id="source-element" class="chat-body">
            <!-- 聊天记录 -->
            <view class="chat-item" v-for="(item, index) in msgList" :key="index" :id="'index-' + index">
              <!-- 自己发的消息 -->
              <view class="item self" v-if="item.sender == 'user'">
                <!-- 文字内容 -->
                <view class="content right">
                  <!-- 文件列表 -->
                  <view v-if="item.files && item.files.length !== 0">
                    <my-album :FileList="item.files"></my-album>
                    <my-files :FileList="item.files" />
                  </view>
                  <my-text :text="item.content" />
                </view>
              </view>
              <!-- 机器人发的消息 -->
              <view class="item Ai" v-if="item.sender == 'bot'">
                <!-- 头像 -->
                <view class="ai-avatar" v-if="msgList[index-1].sender != 'bot'">
                  <image class="avatar" src="@/static/img/head_ai.png"></image>
                  <view class="text">小花助手</view>
                </view>
                <!-- 文字内容 -->
                <view class="content left">
                  <view v-if="item.files && item.files.length !== 0">
                    <my-loading :FileList="item.files"></my-loading>
                    <my-album :FileList="item.files"></my-album>
                    <my-files :FileList="item.files" />
                  </view>
                  <my-text :loading="loading" :checkboxShow="checkboxShow" @checkFun="checkFun" @clickHandleSend="handleSend" :text="item.content" />
                  <Animation v-show="item.loading" />
                </view>
              </view>
            </view>
          </view>`
            // this.chosen_chat_list.forEach(item => {
            //     // 绘制列表项
            //     ctx.fillText(item.content, x, y);
            //     // 移动到下一个位置
            //     y += itemHeight;
            // });
            hiddenContainer.innerHTML = this.domContent;

            // 获取源元素
            const sourceElement = document.getElementById("source-element");

            // 使用html2canvas将源元素转换为Canvas图像
            const canvas = await html2canvas(sourceElement);

            // 将转换后的Canvas图像绘制到目标Canvas上
            ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height);
        },

        // 获取图片信息
        getImageInfo(image) {
            return new Promise((req, rej) => {
                uni.getImageInfo({
                    src: image,
                    success: function (res) {
                        req(res)
                    },
                });
            })
        },

        // 获取设备信息
        getSystemInfo() {
            return new Promise((req, rej) => {
                uni.getSystemInfo({
                    success: function (res) {
                        req(res)
                    }
                });
            })
        },

        // 保存图片到相册
        async saveImage() {
            let filePath = uni.getStorageSync('filePath') //从缓存中读取临时文件路径		
            console.log(filePath, "filePath")
            uni.saveImageToPhotosAlbum({
                filePath: filePath,
                success() {
                    uni.showToast({
                        title: '图片保存成功',
                        icon: 'none'
                    })
                },
                fail(e) {
                    uni.showToast({
                        title: '图片保存失败',
                        icon: 'none'
                    })
                }
            })
        }
    },
};

然后是封装notification.js

aaa变量是原本别人的方法,上面是我自己写的,目前还有问题,插件官网wxml-to-canvas | 微信开放文档,需要注意样式问题

对象属性值为对应 wxml 标签的 class 驼峰形式。需为每个元素指定 width 和 height 属性,否则会导致布局错误。

存在多个 className 时,位置靠后的优先级更高,子元素会继承父级元素的可继承属性。

元素均为 flex 布局。left/top 等 仅在 absolute 定位下生效

const wxml = (msgList) => {
    // let wml = `<view class="chatBody">
    // ${msgList.map((item, index) => {
    //     if (item.sender == 'user') {
    //         return `<view class="item self" >
    //         <view class="content right">
    //           <view>${item.content}</view>
    //         </view>
    //       </view>`
    //     } else if (item.sender == 'bot') {
    //         return `<view class="item Ai">
    //         ${(index==0||msgList[index - 1].sender != 'bot' )&& `<view class="aiAvatar">
    //         <image class="avatar" src="@/static/img/head_ai.png"></image>
    //         <view class="text">小花助手</view>
    //       </view>`}
    //         <view class="content left">
    //           <view>${item.content}</view>
    //         </view>
    //       </view>`
    //     }
    // })}
    // </view>`
    let wml = `<view class="chatBody">
    ${msgList.map((item, index) => {
            return item.content
    })}
    </view>`
    console.log('wml', wml);
    return wml
}


// ${msgList.map((item, index) => {
//     if (item.sender == 'user') {
//         return `<view class="item self" >
//         <view class="content right">
//           <view>${item.content}</view>
//         </view>
//       </view>`
//     } else if (item.sender == 'bot') {
//         return `<view class="item Ai">
//         ${(index==0||msgList[index - 1].sender != 'bot' )&& `<view class="ai-avatar">
//         <image class="avatar" src="@/static/img/head_ai.png"></image>
//         <view class="text">小花助手</view>
//       </view>`}
//         <view class="content left">
//           <view>${item.content}</view>
//         </view>
//       </view>`
//     }
// })}

let qita = `
<view v-if="item.files && item.files.length !== 0">
<my-album :FileList="item.files"></my-album>
<my-files :FileList="item.files" />
</view>
<view v-if="item.files && item.files.length !== 0">
<my-album :FileList="item.files"></my-album>
<my-files :FileList="item.files" />
</view>
`

/**
 * @param {*} screenWidth 屏幕宽度
 * @param {*} canvasWidth  画布宽度
 * @param {*} canvasHeight  画布高度
 * @param {*} numberWidth  数字宽度,动态设置
 * @return {*} 
 */
const style = (screenWidth, canvasWidth, canvasHeight) => {
    return {
        "chatBody": {
            width: screenWidth,
            height: canvasHeight,
            // backgroundColor: `linear-gradient(
            //     145deg,
            //     rgba(76, 216, 251, 0.5) 0%,
            //     rgba(255, 255, 255, 0.5) 35%,
            //     rgba(255, 255, 255, 0.5) 26%,
            //     rgba(254, 235, 255, 0.5) 50%
            //   )
            //   bottom right / 50% 50% no-repeat,
            // linear-gradient(
            //     215deg,
            //     rgba(76, 216, 251, 0.5) 0%,
            //     rgba(255, 255, 255, 0.5) 35%,
            //     rgba(255, 255, 255, 0.5) 26%,
            //     rgba(254, 235, 255, 0.5) 50%
            //   )
            //   bottom left / 50% 50% no-repeat,
            // linear-gradient(
            //     325deg,
            //     rgba(76, 216, 251, 0.5) 0%,
            //     rgba(255, 255, 255, 0.5) 35%,
            //     rgba(255, 255, 255, 0.5) 26%,
            //     rgba(254, 235, 255, 0.5) 50%
            //   )
            //   top left / 50% 50% no-repeat,
            // linear-gradient(
            //     35deg,
            //     rgba(76, 216, 251, 0.5) 0%,
            //     rgba(255, 255, 255, 0.5) 35%,
            //     rgba(255, 255, 255, 0.5) 26%,
            //     rgba(254, 235, 255, 0.5) 50%
            //   )
            //   top right / 50% 50% no-repeat,
            // #fff`,
            backgroundColor:"#fff",
            color: '#333',
            fontSize: 14
        },
        "item": {
            boxSizing: 'border-box',
            width: screenWidth,
            height: screenWidth*0.3,//测试
            padding: '12rpx 20rpx',
            display: 'flex',
            flexWrap: 'wrap'
        },
        "self": {
            justifyContent: 'flex-end',
            flex: '1'
        },
        "aiAvatar": {
            width: screenWidth,
            height: screenWidth*0.3,//测试
            display: 'flex',
        },
        "avatar": {
            width: screenWidth*0.1,
            height: screenWidth*0.1,
            display: 'flex',
            justifyContent: 'center',
            borderRadius: '50%',
            overflow: 'hidden',
            margin: '0 6px 6px 0'
        },
        "text": {
            width: screenWidth,
            height: screenWidth*0.1,
            lineHeight: screenWidth*0.1,
            fontSize: 14,
            background: 'linear-gradient(90deg, #fff 0%, #f306fb 0.01%, #0098f0 93.75%)',
            webkitBackgroundClip: 'text',
            webkitTextFillColor: 'transparent',
        },
        "content": {
            width: screenWidth,//测试
            height: screenWidth*1,//测试
            display: 'inline-block',
            wordWrap: 'break-word',
            padding: '12px',
            borderRadius: '16px',
            fontSize: 14,
            fontFamily: 'PingFang SC',
            fontWeight: '400',
            color: '#333333',
            lineHeight: '20px'
        },
        "left": {
            backgroundColor: '#ffffff',
            borderTopLeftRadius: ' 4px !important'
        },
        "right": {
            backgroundColor: '#c2dcff',
            borderTopRightRadius: '4px !important'
        },

        // "container-mm": {
        //     width: canvasWidth,
        //     height: canvasHeight,
        //     position: 'relative',
        //     overflow: 'hidden',
        //     backgroundColor: '#ffffff',
        //     padding: '30rpx 20rpx',
        // },
        // "name": {
        //     fontSize: 20,
        //     color: '#333',
        //     marginLeft: canvasWidth * 0.08,
        //     width: canvasWidth * 0.84,
        //     height: screenWidth * 0.18,
        //     textAlign: 'center',
        // },
        // "content": {
        //     fontSize: 14,
        //     color: '#333',
        //     width: canvasWidth * 0.84,
        //     height: screenWidth * 0.84,
        //     marginLeft: canvasWidth * 0.08,
        //     marginTop: canvasWidth * 0.08,
        // },
        // "pic": {
        //     width: canvasWidth * 0.4,
        //     height: screenWidth * 0.2,
        //     marginTop: canvasWidth * 0.1,
        //     marginLeft: canvasWidth * 0.35,
        //     marginBottom: canvasWidth * 0.05,
        //     borderRadius: screenWidth * 0.14,
        //     overflow: 'hidden',
        // },
    }
}

module.exports = {
    wxml,
    style
}

在页面中使用 混入方法

import sharrChatRecord from "./sharrChatRecord.js";
mixins: [sharrChatRecord], 

Uniapp使用wxml-to-canvas进行动态页面转图片 下载资源文件,将文件中的内容直接放在项目的根目录。(1)在程序根目录下新建。(2)将上面的链接中。 阅读详情

相关推荐

Uniapp中使用wxml-to-canvas生成分享图的避坑指南

本文详细解析了在Uniapp中使用wxml-to-canvas组件将动态页面转换为高质量分享图片的完整流程与核心技巧。针对动态数据绑定、样式适配、画布尺寸计算、图片资源加载等常见痛点,提供了从环境搭建、模板构建到性能优化的系统解决方案,并重点探讨了如何规避真机渲染模糊、布局错乱等关键问题,助力开发者高效实现稳定、精美的分享图生成功能。

weixin_29306875的博客 226

微信小程序插件--wxml-to-canvas(生成图片)

小程序内通过静态模板和样式绘制 canvas ,导出图片,可用于生成分享图等场景

别告诉我有Bug 1万+

Uniapp中使用wxml-to-canvas避坑指南:动态页面转图片的常见问题与解决方案

本文深入探讨了在Uniapp中使用wxml-to-canvas将动态页面转换为图片的高效解决方案。针对开发中常见的布局错乱、图片加载失败等问题,提供了详细的配置指南、性能优化策略和跨平台兼容性处理方法,帮助开发者快速实现动态内容转图片功能。

weixin_29206669的博客 268

释放创造力!探索微信小程序中的wxml-to-canvas绘图组件

开发者可以使用组件将用户输入的信息和模板合成为自定义的海报或名片,提升用户体验。

青轩桃李能几何,流光欺人忽蹉跎 4805

uni-app小程序实战:基于wxml-to-canvas的动态海报生成与权限处理全解析

本文详细解析了在uni-app小程序中利用wxml-to-canvas实现动态海报生成的全过程,包括项目初始化、组件集成、模板设计、权限处理及性能优化。通过实战案例展示如何解决跨端兼容性问题,提升用户分享体验,适用于社交、电商等多种场景。

weixin_42567752的博客 327

微信小程序绘画学习平台开发实战:从Canvas绘制到调试交付全流程

微信小程序作为轻量级应用形态,凭借无需安装、触控支持完善、微信生态集成等优势,成为绘画学习类工具的理想载体。Canvas 2D接口为自由绘画、分步骤临摹等核心功能提供了底层能力保障,而合理的架构设计——如画板组件化封装、线段栈式撤销重做、动态导航栏适配——则决定了项目的可维护性与演示稳定性。在工程实践中,真机调试与文档交付往往比编码本身更影响项目完成度,涉及手机号授权、相册权限、合法域名配置等高频踩坑点。打磨一个可交付的小程序项目,本质上是在验证开发者的调试链路与问题排查能力。本文以绘画学习平台为例,系统梳

weixin_35734408的博客 245

uniapp使用wxml-to-canvas开发小程序保存canvas图片

uniapp使用wxml-to-canvas开发小程序保存页面为图片、常用保存为海报图。

明月几时有?把酒问青天。不知天上宫阙,今夕是何年。我欲乘风归去,又恐琼楼玉宇,高处不胜寒。起舞弄清影,何似在人间。转朱阁,低绮户,照无眠。不应有恨,何事长向别时圆?人有悲欢离合,月有阴晴圆缺,此事古难全。 但愿人长久,千里共婵娟。 6642

微信小程序 uni-app wxml-to-canvas 小程序内通过静态模板和样式绘制 canvas ,导出图片,可用于生成分

wxml-to-canvas 小程序内通过静态模板和样式绘制 canvas ,导出图片,可用于生成分享图等场景

Uniapp结合wxml-to-canvas实现动态页面截图与分享功能

本文详细介绍了如何在Uniapp项目中集成wxml-to-canvas组件,实现将动态页面内容高效、高质量地转换为图片,以满足电商海报、社交分享等场景的需求。文章从环境搭建、核心代码实现到性能优化与避坑指南,提供了完整的实战解决方案,重点解决了动态页面转图片这一核心痛点。

weixin_29304985的博客 251

有限状态机FSM详解(一)

有限状态机在维基百科中的解释是: 有限状态机(英语:finite-state machine,缩写:FSM)又称有限状态自动机,简称状态机,是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型。 至于为什么要学FSM,FSM可以把模型的多状态、多状态间的转换条件解耦。可以使维护变得容易,代码也更加具有可读性,也更加艺术。 理解有限状态机首先需要理解整个模型。我们把灯的开关作为示例,...

benjonc的博客 5万+

NVIDIA Jetson AGX Xavier设置风扇转速、工作模式及性能监控

Xavier的风扇在开机之后是默认关闭的,每次重启都需要手动打开风扇,后续可能考虑修改bashrc文件进行自动开启 这个是显示当前风扇的转速,默认应该是0,表示关闭,最大是250 cat /sys/devices/pwm-fan/target_pwm 可以通过修改该文件的值来修改风扇转速 vim /sys/devices/pwm-fan/target_pwm 我一般使用的是100这个值 作者:ryan_ren 链接:https://www.jianshu.com/p/d3c2041f7f7d 来源:简书 著

weixin_43877080的博客 1万+

微信小程序中使用wxml2canvas时遇到save canvas error的问题

【代码】微信小程序中使用wxml2canvas时遇到save canvas error的问题。

z19960925的博客 768

利用netmq在相机应用于unity之间传输图像数据

Unity工业相机接入方案解析 本文探讨了在Unity中接入不同品牌工业相机的技术方案。研究发现: Basler相机可直接调用官方DLL(pylonc.net.dll)实现接入 海康和大恒相机因驱动DLL依赖C++组件,无法直接调用 解决方案:通过独立进程(相机应用程序)与Unity进行通信,采用NetMQ实现图像数据传输 技术实现要点: 相机端:使用PublisherSocket发布JPEG图像帧 Unity端:通过SubscriberSocket订阅图像数据 优化:设置高水位线控制缓存帧数,避免数据堆积

weixin_46450859的博客 425

前端 canvas 在微信小程序、uniapp、vue及jsp中的用法

前端在不同框架内使用canvas合成图片、海报等

m0_68964998的博客 1355

差分音频转单端音频单电源方案

其中,芯片设计中的轨到轨输出(Rail-to-Rail Output) 是指通过特定的电路设计,使芯片(如运算放大器、驱动电路等)的输出电压能够达到或接近电源电压的上下极限(即“电源轨”),从而最大化信号的动态范围。最终,Vout=R2/R1*(Vin2−Vin1),即输出电压为输入电压差(Vin2−Vin1)乘以电阻比R2/R1。2、电阻:R1、R2、R3、R4是电路中的电阻,其中R1 = R3,R2 = R4。因R1=R3,R2=R4,且Vn=Vp,设R1=R3=R,R2=R4=kR。

电子绿洲的博客 4990

告别OFDM卡顿:用MATLAB手把手仿真AFDM波形,搞定高铁、无人机通信的时变信道难题

本文详细介绍了如何使用MATLAB仿真AFDM波形,解决高铁和无人机通信中的时变信道难题。通过仿射变换技术,AFDM在多普勒频移严重的场景下表现优异,显著提升通信质量。文章包含参数配置、波形生成、性能对比等实战内容,适合通信工程师和研究人员参考。

weixin_27014595的博客 331

把view或者div绘制 canvas ,导出图片功能实现完整源码附效果图(兼容H5和小程序)

先看下效果图:(上面灰色块内的用div和CSS写出来的,然后绘制到canvas) 实现此功能需要使用到一个微信小程序的插件,插件官方文档地址: wxml-to-canvas | 微信开放文档 本博客代码环境,uniapp(vue) 实现流程: 1.创建uniapp项目,命名为 (htmlToCarvasDemo) 2.Alt + C 打开终端,运行npm i x-wxml-to-canvas,安装插件 npm ix-wxml-to-canvas 3.在index目录添加,d..

a_靖的博客 4918

BugkuCTF-PWN题pwn2-overflow超详细讲解

解题思路 1)计算出get_shell_的地址偏移量 2)算出来之后就直接溢出到后门函数 知识点 x64函数调用规则 解题之前我们先学下linux x64的函数调用规则。 x64机器在调用某个函数前,比如int func(int a, int b, int c, int d, int e, int f, int g, int h),首先他会把前6个参数从左往右存入到寄存器rdi、rsi、rdx、rcx、r8、r9,其余参数存入到栈里,保存的顺序是从右往左入栈。比如abcdef会存入到寄存器里,然后一次入栈h

am_03的博客 3023

UniApp跨端集成ECharts实战:Canvas桥接与动态加载方案

ECharts作为主流JavaScript可视化库,其在跨平台框架中的适配始终是前端工程化难点。理解ECharts的Canvas渲染原理与生命周期钩子联动机制,是实现H5、微信小程序、支付宝小程序及App多端一致图表展示的技术基础。本文聚焦UniApp生态下ECharts集成的核心矛盾——DOM缺失与canvas上下文不兼容,并基于setCanvasCreator接口和uni.createCanvasContext API,构建轻量、可复用、低维护成本的跨端图表组件。方案兼顾首屏性能(动态加载)、尺寸自适应

weixin_28675661的博客 227

CentOS 7.9安装python3.11

CentOS 7.9安装python3.11

leafseelight的专栏 1347

Vanna 2.0:基于LLM的智能文本到SQL框架,实现企业级数据查询与权限控制

文本到SQL技术是自然语言处理与数据库交互的重要桥梁,它允许用户使用日常语言直接查询数据库,无需编写复杂的SQL语句。其核心原理是利用大语言模型理解用户意图,并结合检索增强生成技术,将自然语言问题转换为准确的结构化查询语言。这项技术的价值在于大幅降低了数据访问门槛,提升了业务人员的数据自助分析能力,并能在金融分析、销售报表、运营监控等场景中实现实时数据洞察。Vanna 2.0作为一个开源框架,通过引入用户感知的智能体架构和行级安全策略,解决了企业级应用中的多租户数据隔离与权限控制等关键问题,使得自然语言数据

weixin_42629522的博客 556

UniApp微信小程序测试全攻略:从模拟器到真机的完整质量保障

在跨端应用开发中,测试是保障产品质量的关键环节,它贯穿于从编码到上线的整个生命周期。其核心原理在于通过模拟真实运行环境,验证应用在不同平台、设备和网络条件下的功能、性能与兼容性。对于采用Vue.js生态的UniApp开发者而言,掌握高效的测试方法具有重要技术价值,它能将开发成果从“可运行代码”转化为“稳定可靠的产品”,直接影响用户体验和项目成功率。测试实践通常覆盖模拟器快速调试、小程序端真机验证以及原生App端兼容性测试等多个应用场景。其中,**真机测试**是暴露环境差异问题的最终手段,而**远程调试**则

weixin_30699955的博客 524

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

UniApp开发微信小程序健康管理:架构设计、数据模型与踩坑实录

在移动应用开发中,跨端框架解决了多平台复用的核心痛点,其中UniApp基于Vue语法编译到微信小程序、App和H5,兼顾开发效率与原生性能。健康管理类工具需要高频记录饮食、运动数据并进行卡路里计算,借助UniApp的组件化架构和Pinia状态管理,可以快速搭建稳定的数据模型与页面流转。实际开发中还需重点处理日期解析的iOS兼容性、主包体积分包策略以及真机日志调试等关键问题。本文以一款饮食运动管理小程序为例,从技术选型、数据表设计到核心功能实现与上架审核,完整梳理了跨端开发在微信小程序生态中的落地经验,为同类

weixin_36474966的博客 291

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

UniApp开发微信小程序实战:小学生阅读交流系统设计与踩坑指南

跨端开发框架UniApp凭借Vue语法和多端编译能力,正在成为小程序开发的热门选择,尤其适合需要兼顾微信小程序、H5乃至App的项目。文章从UniApp的核心原理出发,解析其与原生小程序的差异及技术选型思路,并延伸到实际工程中常见的路由参数、自定义导航、表单校验、图表渲染、扫码、键盘遮挡等高频问题。通过一个面向小学生的阅读交流系统案例,展示书单推荐、阅读打卡、读后感审核、数据报告等功能的设计与实现,同时给出打包上架、隐私合规、审核避坑等实践经验。无论是毕业设计还是商业项目,掌握UniApp都能有效降低多端维

weixin_34050005的博客 438

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

微信小程序实战:从零开发彩色消除小游戏

二维数组是许多前端交互场景的核心数据结构,通过行列索引可以直观映射到页面网格。在游戏开发中,网格类玩法往往依赖连通块查找算法来判定相同元素的相邻关系。理解这些基础算法,不仅有助于实现消消乐、消除类产品,还能提升对状态管理和渲染性能的把控能力。以微信小程序为运行环境,借助WXML和JavaScript可以快速搭建一个彩色消除小游戏,其核心逻辑包括棋盘渲染、点击检测、连通块消除、重力下落与计分反馈。小程序无需后端即可运行,适合作为入门项目掌握原生开发流程。从页面初始化到真机调试的完整过程将被逐步拆解,帮助开发者

cigang4063的博客 521
上一篇: 粗暴自适应
下一篇: uniapp vue2 微信小程序项目使用canvas绘制画布并导出图片
Akil_
博客等级 码龄5年 6粉丝 6原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址