小程序
小游戏
企业微信
微信支付
扫描小程序码分享
canvas.measureText()方法好像是被废弃的,使用的时候,只有编译有效果,能计算出字体的宽度,打出的log,是有数据的,但是真机调试、预览和体验版本好像都没用。然后我打了log,试试真机,显示的数据都是0,有大佬知道是怎么回事吗?或者有大佬知道测量字体宽度的新的方法吗?
附上图片:
1 个回答
加粗
标红
插入代码
插入链接
插入图片
上传视频
你好,麻烦通过点击下方“反馈信息”按钮,提供出现问题的。
onLoad() {
wx.createSelectorQuery().select('#canvas').fields({ node: true, size: true }).exec((res) => {
// Canvas 对象
const canvas = res[0].node
// Canvas 画布的实际绘制宽高
const renderWidth = res[0].width
const renderHeight = res[0].height
// Canvas 绘制上下文
const ctx = canvas.getContext('2d')
// 初始化画布大小
const dpr = wx.getWindowInfo().pixelRatio
canvas.width = renderWidth * dpr
canvas.height = renderHeight * dpr
ctx.scale(dpr, dpr)
// 绘制前清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 若干绘制调用
ctx.font = "48px serif";
ctx.fillText("Hello world", 10, 50);
ctx.strokeText("Hello world", 10, 150);
var text = ctx.measureText("Hello world"); // TextMetrics object
console.log(text.width)
})
}
关注后,可在微信内接收相应的重要提醒。
请使用微信扫描二维码关注 “微信开放社区” 公众号
onLoad() {
wx.createSelectorQuery().select('#canvas').fields({ node: true, size: true }).exec((res) => {
// Canvas 对象
const canvas = res[0].node
// Canvas 画布的实际绘制宽高
const renderWidth = res[0].width
const renderHeight = res[0].height
// Canvas 绘制上下文
const ctx = canvas.getContext('2d')
// 初始化画布大小
const dpr = wx.getWindowInfo().pixelRatio
canvas.width = renderWidth * dpr
canvas.height = renderHeight * dpr
ctx.scale(dpr, dpr)
// 绘制前清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 若干绘制调用
ctx.font = "48px serif";
ctx.fillText("Hello world", 10, 50);
ctx.strokeText("Hello world", 10, 150);
var text = ctx.measureText("Hello world"); // TextMetrics object
console.log(text.width)
})
}