uni-app中const canvas = this.$refs.firstCanvas; 设置宽高无效, 使用 ctx.scale(dpr, dpr); 会导致图片不显示
uni-app中const canvas = this.$refs.firstCanvas; 设置宽高无效, 使用 ctx.scale(dpr, dpr); 会导致图片不显示
代码示例
methods: {
handleGetCanvasFields() {
return new Promise((resolve, reject) => {
const query = uni.createSelectorQuery().in(this);
query.select(`#firstCanvas`).fields({
size: true,
}, (res) => {
const width = res.width
const height = res.height
this.canvas = {
width,
height
}
resolve()
}).exec()
})
},
handleGetCanvasNode() {
const ctx = uni.createCanvasContext("firstCanvas", this);
const canvas = this.$refs.firstCanvas; // 获取 canvas 元素
// 确保 canvas 元素的物理尺寸设置正确
const dpr = uni.getSystemInfoSync().pixelRatio;
const width = this.canvas.width * dpr;
const height = this.canvas.height * dpr;
// 设置 canvas 元素的宽高
canvas.width = width;
canvas.height = height;
// 确保上下文缩放与设备分辨率匹配
ctx.setStrokeStyle("#ff0000");
ctx.setLineWidth(2);
ctx.scale(dpr, dpr); // 缩放使其适配高分辨率设备
// 开始绘制图形
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(130, 100);
ctx.lineTo(140, 70);
ctx.stroke();
ctx.draw(); // 确保绘制完成
}
}
项目信息
信息 | 值 |
---|---|
创建方式 | uni-app |
版本号 | 未提及 |
开发环境 | 未提及 |
更多关于uni-app中const canvas = this.$refs.firstCanvas; 设置宽高无效, 使用 ctx.scale(dpr, dpr); 会导致图片不显示的实战教程也可以访问 https://www.itying.com/category-93-b0.html
1 回复