【发布时间】:2021-07-20 15:44:05
【问题描述】:
我是 HTML 和 javascript 的新手,我试图用一系列矩形填充 HTML5 画布,每个矩形的高度都在增加,并且每个矩形都与前一个相邻。我想让我的代码在各种屏幕尺寸上运行,因此我从 javascript 中动态找到画布的宽度和高度。我希望用户将来输入条形“n”的数量。这是我尝试过的。
//fucntion to draw the rectangles
function draw(ctx,x,y,b,l){
ctx.beginPath();
ctx.rect(x,y,b,l);
ctx.fill();
}
const c = document.querySelector("#my-canvas");
const ctx = c.getContext("2d");
//getting the height and widdth of the canvas
const cWidth = c.getBoundingClientRect().width;
const cHeight = c.getBoundingClientRect().height;
//number of bars/rectangles to be drawn
let n=10;
//calculating the width of each rectangle
let width = cWidth/n;
for(i=0;i<n;i++){
draw(ctx,i*width,0,width,5*(i+1));
}
<!DOCTYPE html>
<html>
<head>
<style>
#my-canvas{
position:relative;
background: coral;
height:70vh;
width:70vw;
top:15vh;
left:15vw;
}
</style>
</head>
<body>
<canvas id="my-canvas"></canvas>
<script src="tempCodeRunnerFile.js"></script>
</body>
</html>
这根本没有给出所有的条,有时它给了我 3 个其他时间 5 或 8,它随着浏览器和平台的变化而变化(JS-fiddle 在 chrome 上给我 5,在 firefox 上给我 7.5 这是代码@ 987654321@),在我的电脑上它给出 2-3。
我有两个问题:
- 这里有什么问题,如何解决?
- 有没有更好的方法在 vanilla javascript 中执行此操作,因为我不知道任何其他库/框架
PS:对不起,如果这是一个重复的问题,我用我有限的英语找不到任何问题。
【问题讨论】:
标签: javascript html css html5-canvas