我的想法是使用PHP或JS创建大量DIV。(我从昨天开始写JS。)
因此,我的自我给定任务是使用PHP或JS或两者两者生成DIV的网格。到目前为止,这个想法是将一个通用的div作为行和小单元。首先,我确定该行必须使用多长时间,然后定义行数[到目前为止]。当我产生电网时,我的问题就来了。仅使用PHP非常慢,因此我决定也使用JS。我的第一次尝试导致将时间切成两半,但仍然缓慢。所以我问自己,有没有办法将JS的工作分开?好吧,是的...当然可以使用功能!因此,我制作了一个名为Sector的函数,并试图称呼它。它起作用了,但仍然太慢了。那么,做这种事情的最佳实践是什么?
<?php
$rowWidth = 200; // width in pixels
$rowHeight = 100; // height in pixels
$boxWidth = 1; // box width in pixels
$boxHeight = 1; // box height in pixels
?>
<body>
<script>
function sector(sector) {
for (var i = 0*sector; i < (<?php echo $rowHeight / 100 ?> + 100*sector); i++) { // trying to manage sectors
var div = document.createElement('div');
// set style
div.style.width = '<?php echo $rowWidth ?>';
div.style.height = '<?php echo $boxHeight ?>';
div.style.background = 'red';
div.setAttribute('class', 'row'); // and make a class for future css (for now using inline css set by js)
div.setAttribute('id', 'row'+i); // and make an id selector
document.body.appendChild(div);
for (var e = 0; e < <?php echo $rowWidth ?>; e++) {
var box = document.createElement('div');
// set style
box.style.width = '<?php echo $boxWidth ?>';
box.style.height = '<?php echo $boxHeight ?>';
box.style.float = 'left';
box.style.background = 'pink';
box.setAttribute('class', 'box'); // and make a class for future css (for now using inline css set by js)
box.setAttribute('id', 'box'+e); // and make an id selector
document.getElementById('row'+i).appendChild(box); // joining my row
}
}
}
<?php for ($sector=0; $sector < ($rowWidth / 100) ; $sector++) { ?>
//calling all sectors, calling all sectors... please report
sector(<?php echo $sector+1 ?>);
<?php } ?>
</script>
</body>
更新:这看起来与我的想法相似。
http://www.businessinsider.com/reddit-place-place-place-prils-fools-experiment-creates-pixel-art-art-final-vinn-finter-version-2017-4
他们是如何做到的?
如果您的目的是显示图像,您将在其中设置单个像素,那么您将使用帆布元素获得更好的结果。
这是一些演示:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
function draw() {
ctx.putImageData(imgData, 0, 0);
}
function setPixel(x, y, red, green, blue) {
var offset = (y * canvas.width + x) * 4;
imgData.data[offset] = red;
imgData.data[offset+1] = green;
imgData.data[offset+2] = blue;
imgData.data[offset+3] = 255; // opacity
}
// Example: set some green pixels along a line
for (var i = 0; i < 200; i++) {
setPixel (i, i >> 2, 0, 128, 0);
}
draw(); // display the result.
<canvas id="canvas" width="500" height="180"></canvas>
您的PHP脚本应设置帆布元素(HTML)的宽度和高度属性,并提供坐标和相应的颜色代码以传递给setPixel()
。显然,让PHP以简洁的格式提供该信息以最大程度地减少流量。
如果您的数据库可以存储位图格式,则可以使用<img src="...">
元素加载该格式并完成。下一个最好的是,您的数据库将数据存储为向量,而您只需要绘制一些行和矩形,这比必须通过&amp&amp;的资源更少。绘制每个像素。