HTML5 画布,在溢出时添加滚动条

html5 canvas, add scrollbar on overflow

本文关键字:添加 滚动条 溢出 画布 HTML5      更新时间:2023-09-26

你好,我有一个html画布,我想添加一个滚动条,就像任何网页或文本区域一样,我使用了溢出:滚动;但它只显示滚动条并且它们被禁用(我无法滚动)

这是标记

<div class="ccsp-area">
    <canvas id="mainCanvas" width="900" height="500"></canvas>
</div>

这是CSS(SCSS)

 .ccsp-area {
   width: 90%;
   height: 100%;
   display: inline-block;
   canvas {
     display: inline-block;
     background-color: #fff;
     max-width: 100%   !important;
     overflow: scroll;
   }
 }

最后这是 JS

var canvas = $("#mainCanvas");
var ctx = canvas[0].getContext('2d');
var targetSizeE = $(".ccsp-area");
var rwidth = targetSizeE.width() -200;
var rheight = targetSizeE.height() -80;
// no need to read more code after this stage
canvas.attr('width', rwidth);
canvas.attr('height', rheight);
ctx.beginPath();
ctx.moveTo(100 , 100);
ctx.lineTo(600, 600);
ctx.lineTo(600,100);
ctx.closePath();
ctx.lineWidth = 20;
ctx.strokeStyle = "rgba(10,220,50,1)";
ctx.fillStyle = "rgba(10,220,50,0.5)";
ctx.stroke();

结果的屏幕截图结果

如您所见,滚动条被禁用,即使画布内的图纸超过画布的高度,我也无法滚动。

正如那家伙所说,画布没有内容可以溢出因此,最好的方法是将画布宽度和高度设置为非常大的值,可能是 2200 x 1500(您可以通过 js 更改高度)

这就是你的css应该是什么样子

的。
.ccsp-area {
  width: 90%;
  height: 100%;
  display: inline-block;
  overflow: scroll;
  canvas {
    display: inline-block;
    background-color: #fff;
  }
}

在您的情况下,从 html 元素而不是从 JS 设置大小(也可以随意删除设置画布大小的 js 代码)

<canvas id="mainCanvas" width="900" height="500"></canvas>

在此处查看链接

您可以分别设置overflow-xoverflow-y

查看更多关于 MDN 溢出的信息