Javascript 在任意位置无需触摸即可绘制图像
我认为图片将是比文字更好的例子 当我使用随机数时,我得到了不正确的结果 但我想得到这个结果: 我发现了这样的东西:Javascript 在任意位置无需触摸即可绘制图像,javascript,html5-canvas,Javascript,Html5 Canvas,我认为图片将是比文字更好的例子 当我使用随机数时,我得到了不正确的结果 但我想得到这个结果: 我发现了这样的东西: $(document).ready(function() { var containerW = 700; var containerH = 600; var positions = []; $('.picture').each(function() { var coords = { w: $(this).out
$(document).ready(function() {
var containerW = 700;
var containerH = 600;
var positions = [];
$('.picture').each(function() {
var coords = {
w: $(this).outerWidth(true),
h: $(this).outerHeight(true)
};
var success = false;
while (!success)
{
coords.x = parseInt(Math.random() * (containerW-coords.w));
coords.y = parseInt(Math.random() * (containerH-coords.h));
var success = true;
$.each(positions, function(){
if (
coords.x <= (this.x + this.w) &&
(coords.x + coords.w) >= this.x &&
coords.y <= (this.y + this.h) &&
(coords.y + coords.h) >= this.y
)
{
success = false;
}
});
}
positions.push(coords);
$(this).css({
top: coords.y + 'px',
left: coords.x + 'px'
});
});
});
如何改进这一点?一种更简单、更快的方法是使用网格约束,其中每个单元都比形状大一点。然后在每个单元格中随机放置一个形状 这里唯一的限制是形状绑定到特定结构,因为形状永远不会移动到周围区域 网格解决方案示例 var ctx=c.getContext2d, cellsX=10, cellsY=5, cellW=c.宽度/cellsX, cellH=c.高度/cellsY, padding=2,//每个形状之间的最小间距 shapeMaxW=cellW>>1,//这些形状大小是任意的 shapeMaxH=cellH>>1; 函数渲染{ c、 宽度=c.宽度; forvar i=0;i