簡體   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