微信小程序canvas如何自适应宽高?
前端显示
生成后正常:
所以问题应该是处在canvas标签这:尝试过使用rpx,没什么用
<canvas id="myCanvas" type="2d" :style="'text-align: center;margin: 0 auto;background-color: black;'"></canvas>
下边的代码,生成的图片无误,但是页面显示的图片是有问题的, 我大概知道是canvas 是没有rpx的适应的。
addwater() {
let that=this;
wx.chooseImage({
count: 1, // 最多可选1张图片
success: function(res) {
// console.log(res);
const tempFilePathss = res.tempFilePaths;
// 获取选中图片的本地临时文件路径
const tempFilePath = res.tempFilePaths[0];
// 创建选择器查询对象
const query = wx.createSelectorQuery();
// 查询canvas组件
wx.getImageInfo({
src: tempFilePathss[0],
success: function (infoRes) {
that.imgWidth = infoRes.width;
that. imgHeight = infoRes.height;
console.log('图片宽度:', that.imgWidth);
console.log('图片高度:', that.imgHeight);
},
fail: function (error) {
console.log('获取图片信息失败:', error);
}
});
query.select('#myCanvas').fields({ node: true, size: true }).exec(function(res) {
const canvas = res[0].node;
const ctx = canvas.getContext('2d');
// 创建图片对象
const img = canvas.createImage();
img.onload = function() {
// 设置canvas大小为图片大小
canvas.width = img.width;
canvas.height = img.height;
// 将图片绘制到canvas上
ctx.drawImage(img, 0, 0, img.width, img.height);
// 在图片上添加文字水印
that.addWatermark(canvas, '仅供办理业务使用'); // 添加水印
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
canvas:canvas,
success: function(res) {
// 保存图片到本地
console.log(res.tempFilePath);
},
fail: function(error) {
console.log('导出图片失败:', error);
}
});
};
// 设置图片路径
img.src = tempFilePath;
// console.log(tempFilePath);
});
},
});
}