Canvas 基础(二)—— 滚动条问题

canvas 系列:

Canvas 绘制图片不显示问题

Canvas 基础(一)

Canvas 基础(二)—— 滚动条问题

 

一般在使用 canvas 的时候,都会设置为容器的宽高,这样可以撑满容器。

但是设置完成后总是会出现滚动条?怎么回事?

复现问题

下面是 canvas 动态获取父级容器的宽高,代码如下(vue):

复制代码
<template>
  <div ref="Box" >
    <canvas id="tempCanvas" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 1000,
      canvasHeight: 500
    }
  },
  mounted() {
    this.canvasWidth = this.$refs.Box.clientWidth
    this.canvasHeight = this.$refs.Box.clientHeight


      const canvasEle = document.getElementById('tempCanvas')
      canvasEle.width = this.canvasWidth
      canvasEle.height = this.canvasHeight
      canvasEle.style.width = this.canvasWidth + 'px'
      canvasEle.style.height = this.canvasHeight + 'px'
  }
}
}
</script>
复制代码

这里关于使用容器的 clientWidth 还是 offsetWidth 可以参考这里:js的offsetWidth、clientWidth是什么

这样设置的时候需要同时设置 canvas 的 width、height 和 style 的 width、height,具体可以看本系列上一篇。

这样完成后,会出现滚动条:

 

F12查看,width、height 和父级完全一样。

解决问题

仔细查看 canvas 的样式,发现 display 的默认值是:inline

 

试着修改 display 的值为:block,滚动条消失了!!!

虽然解决了问题,可是是什么原因呢?

这就要对 CSS 比较有深入的了解。

其实具体的解决方法还有:

  1、父元素设置:font-size:0; 或者 line-height:0; 

  2、当前元素设置:vertical-align: bottom;

具体分析可以看 行内可替换元素滚动条问题

posted @   漠里  阅读(2886)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
历史上的今天:
2021-05-31 uni-app 获取 cookie 问题
点击右上角即可分享
微信分享提示