繁体   English   中英

在 HTML5 canvas 中绘制一系列矩形以完全填充 canvas

[英]Drawing a series of rectangles in HTML5 canvas to completely fill the canvas

我是 HTML 和 javascript 的新手,并试图填充 HTML5 ZFCC790C72A86190DE1B549D0DDC6F55C 的每个矩形与下一个系列的高度和每个矩形。 我想让我的代码在各种屏幕尺寸上运行,因此我从 javascript 动态地找到 canvas 的宽度和高度。 我希望用户将来输入条形“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 这是代码https:// jsfiddle.net/8b9a4de5/ ),在我的电脑上它给出了 2-3。

我有两个问题:

  1. 这里有什么问题以及如何解决这个问题?
  2. 有没有更好的方法在香草 javascript 中做到这一点,因为我不知道任何其他库/框架

PS:对不起,如果这是一个重复的问题,我用有限的英语找不到任何问题。

使用c.getContext("2d")获得的 CanvasRenderingContext2D object 将画布的widthheight属性用于其绘图表面尺寸。 它们没有在您的代码中定义。

您可以在绘制任何内容之前添加以下内容:

c.width = c.offsetWidth;
c.height = c.offsetHeight;

然后问题就解决了。

我在这里稍微简化了你的 js 代码

 window.addEventListener('load', _e => { //function to draw the rectangles function draw(ctx, x, y, b, l) { ctx.fillRect(x, y, b, l); } const c = document.querySelector("#my-canvas"); c.width = c.offsetWidth; c.height = c.offsetHeight; //number of bars/rectangles to be drawn const n = 10; //calculating the width of each rectangle const width = c.width / n; console.log(`${n} rects on w=${c.width} => ${width}`) const ctx = c.getContext("2d"); for (let i = 0; i < n; i++) { draw(ctx, i * width, 0, width, 5 * (i + 1)); } });
 #my-canvas{ position: relative; background: coral; height: 70vh; width: 70vw; top: 15vh; left: 15vw; }
 <!DOCTYPE html> <html> <head></head> <body> <canvas id="my-canvas"></canvas> </body> </html>

编辑:更多解释

我在这里指的是 MDN 文档https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage

Canvas 的默认大小 (w*h) 为 300x150。 这也是其渲染上下文的像素大小,无论使用 CSS 设置什么。 如果不同,则渲染将被缩放以适合元素的大小。

在此示例中,我使用 Javascript 将<canvas>widthheight属性与屏幕上 DOM 元素的实际大小对齐。 我在window.load的处理程序中执行此操作,以确保在执行脚本之前呈现 CSS

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM