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 @ 2022-05-31 14:28  漠里  阅读(2646)  评论(0编辑  收藏  举报