javascript - 为什么我在 Canvas 下看到 div 的背景

标签 javascript css

我正在尝试在 div 内滚动 Canvas 。问题是,当我尝试滚动时,我看到下面 div 的红色背景的红线部分,而不是我希望看到的一切都是黑色的。

HTML:

   <div id="Div1" style=" float: left; width: 150px; height: 200px; background: red; overflow:scroll; ">
    <canvas id="myCanvas1" width="200px" height="500px" style="border:0px solid #ff0000;">asdf asd as asfqwe asd asdfasdf asd as asfqwe asd asdfasdf asd as asfqwe asd asdf</canvas>
</div>

JavaScript:

 var c = document.getElementById("myCanvas1");
    var ctx = c.getContext("2d");
    ctx.fillRect(0, 0, 200, 500);
    ctx.fillStyle = "#00ff00";  //<======= here
    ctx.font = '35px serif';
    ctx.fillText('Hello world', 0, 40);

CSS:

canvas { border: 0px solid black; }

这是一个最小的例子: https://jsfiddle.net/alessio211734/vL4whdc0/17/

最佳答案

添加display: block;canvas

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");
ctx.fillRect(0, 0, 200, 500);
ctx.fillStyle = "#00ff00"; //<======= here
ctx.font = '35px serif';
ctx.fillText('Hello world', 0, 40);
canvas {
  border: 0px solid black;
display: block;
}
<div id="Div1" style=" float: left; width: 150px; height: 200px; background: red; overflow:scroll; ">
<canvas id="myCanvas1" width="200px" height="500px" style="border:0px solid #ff0000;">asdf asd as asfqwe asd asdfasdf asd as asfqwe asd asdfasdf asd as asfqwe asd asdf</canvas>
</div>

关于javascript - 为什么我在 Canvas 下看到 div 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183280/

相关文章:

php - $.get 不返回 html

javascript - 为什么 id = sub 显示值的 div 是 ""而不是 none

javascript - Google App Script setTimeout 函数问题

javascript - ReactJS:如何不断检查本地存储中的 token 是否已过期?

javascript - 如何使用 vuex 进行响应式更新

javascript - 当允许自定义页眉和页脚时,我们是否应该剥离 JavaScript?

javascript - 使用 Javascript 显示 HTML 中的值

javascript - Chrome 扩展程序可在按下图标时触发点击事件

javascript - 在点击上传 javascript/jquery 之前显示图像

html+css usemap 不起作用