问题
在使用canvas时发现其宽高无法政策设置
业务代码
逻辑代码
initCanvas() {
const canvas = document.getElementById('my_canvas');
canvas.width = 500; // 设定canvas的宽度、高度
canvas.height = 500;
const ctx = canvas.getContext('2d');
const img1 = new Image();
img1.src = `${process.env.PUBLIC_URL}/images/checkBook.png`;
img1.onload = (res) => {
console.log(res);
const { path } = res;
const img = path[0];
const { naturalWidth, naturalHeight } = img;
ctx.drawImage(img1, 10, 10, naturalWidth, naturalHeight);
};
}
UI使用的时material-ui
<Box display="flex" flexDirection="column" flex={1} p={1}>
<canvas id="my_canvas" />
<Box display="flex" alignItems="center" m={1}>
<Button
variant="contained"
color="primary"
onClick={() => {
}}
>
保存图片
</Button>
</Box>
</Box>
浏览器显示
虽然canvas元素的宽高是500,但是我不知道为什么赋予了它clientHeight和clientWidth为701
后来发现是父层的flex影响,只要去掉父层的flex布局,或是给canvas外层加上一层div包裹就能解决问题,暂时不知道是什么原因导致的,在这里记录一下