微信小程序中获取页面的实际宽高和rpx的关系getSystemInfoSync

本文介绍如何使用小程序的getSystemInfoSync方法获取屏幕信息,包括屏幕宽度、高度、状态栏高度等,并详细解释了如何将这些信息从px单位转换为rpx单位,以便在小程序中更灵活地进行布局设计。

小程序提供了一个方法叫getSystemInfoSync,通过它可以获取当前屏幕信息

const info = wx.getSystemInfoSync();
const 与rpx的比值 = 750 / systemInfo.windowWidth;
const 屏幕宽度 = info.screenWidth;
const 屏幕高度 = info.screenHeight;
const 状态栏高度 = info.statusBarHeight;
const 可用窗口宽度 = info.windowWidth;
const 可用窗口高度 = info.windowHeight;

上面获取的是px为单位的,要是需要设置当前元素的值,需要转换成rxp
如我想要获取当前可用窗口的rpx高度:

实际rpx高度 = 与荣幸的比值 * 可用窗口的高度;
rpxHeight = 750 / systemInfo.windowWidth * info.windowHeight;
convertToImage() { this.$nextTick(() => { const query = uni.createSelectorQuery().in(this); query.select('.share-card').fields({ dataset: true, rect: true, size: true }, (res) => { if (res) { console.log(res.width, 'width'); console.log(res.height, 'height'); // 获取设备像素比,确保清屏下图片清晰 const dpr = uni.getSystemInfoSync().pixelRatio; const canvasId = 'tempCanvas'; const ctx = uni.createCanvasContext(canvasId, this); console.log(dpr, 'dpr'); // 设置 canvas 的尺寸为固定值(600rpx × 1000rpx),并根据设备像素比调整 const canvasWidth = 600 * dpr; const canvasHeight = 1000 * dpr; // 在 Canvas 上绘制一个矩形,左上角坐标为 (0, 0),度为 canvasWidth,度为 canvasHeight ctx.rect(0, 0, canvasWidth, canvasHeight); ctx.setFillStyle('#ffffff'); ctx.fill(); // 绘制背景 ctx.setFillStyle('#ffffff'); ctx.fillRect(0, 0, canvasWidth, canvasHeight); // 绘制文字,根据像素比调整文字大小位置 ctx.setFontSize(40 * dpr); // 调整字体大小 ctx.setTextAlign('center'); ctx.setTextBaseline('middle'); ctx.setFillStyle('#000000'); ctx.fillText(this.shareWord, canvasWidth / 2, 200 * dpr); // 调整文字位置 // 绘制底部文字 ctx.setFontSize(23 * dpr); // 调整字体大小 ctx.setTextAlign('center'); ctx.setTextBaseline('middle'); ctx.setFillStyle('#000000'); ctx.fillText('M Stand,More Than Coffee', canvasWidth / 2, 900 * dpr); // 调整文字位置 // 绘制二维码 const qrCanvasId = 'qrcode'; const qrCtx = uni.createCanvasContext(qrCanvasId, this); qrCtx.drawImage(qrCanvasId, canvasWidth / 2 - 60 * dpr, 400 * dpr, 120 * dpr, 120 * dpr); 生成的图片比例过大导致图片内容显示不全
最新发布
03-28
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值