繁体   English   中英

如何使用javascript在html5 canvas中基于给定计数将图像连续放置?

[英]How to place images in a row based on the given count in html5 canvas using javascript?

如何基于动态给出的图像数量将图像放置在html5画布中的行中,以及如何在行之间分配空间(行数也是动态给出的)?

如果您想像使用javascript一样简单地进行布局,则可以自己进行。 下面的示例根据画布的高度均匀地隔开行,然后在每一行中,矩形按画布的宽度均匀地隔开。 您可以调整浏览器的大小,并观察布局如何移动矩形。

 var imageHeight = 100; var imageWidth = 80; //This defines how many pictures are in each row var rowCount = [ 2, 3, 5 ]; setCanvasSize(); redrawCanvas(); function setCanvasSize() { var can = document.getElementById("myCanvas"); var width = window.innerWidth; var height = window.innerHeight; can.width = width; can.height = height; } function redrawCanvas() { var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); ctx.clearRect(0, 0, width, height); var width = can.width; var height = can.height; // // This is the layout function ------------------------ // //how many pixels per row are available? var pixelsPerRow = height/rowCount.length; for (var y=0;y<rowCount.length;y++) { //draw the yth row: var imagesInRow = rowCount[y]; var pixelsPerImage = width / imagesInRow; for (var x=0;x<imagesInRow;x++) { //now find the center of the cell defined by the //x and y coordinates: var xC = (x * pixelsPerImage) + (pixelsPerImage / 2); var yC = (y * pixelsPerRow) + (pixelsPerRow / 2); //now place the image in the center of the cell by offsetting half of the image's width and height: var xI = xC - (imageWidth / 2); var yI = yC - (imageHeight / 2); //instead of drawing an image, for this example a rectangle is being drawn instead: ctx.fillStyle = "#000"; ctx.fillRect(xI, yI, imageWidth, imageHeight); } } } window.onresize = function() { setCanvasSize(); redrawCanvas(); }; 
 <canvas id="myCanvas"></canvas> 

暂无
暂无

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

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