Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将图元放置在随机位置_Javascript_Html_Canvas - Fatal编程技术网

Javascript 将图元放置在随机位置

Javascript 将图元放置在随机位置,javascript,html,canvas,Javascript,Html,Canvas,我试图用这段代码将一个元素放置在随机位置,但它只是将该元素放置在容器元素的顶部。我做错了什么 create: function(){ console.log("cone created"); var el = document.createElement('div'); el.classList.add('cone'); this.container.appendChild(el); this.el = el; this.x =

我试图用这段代码将一个元素放置在随机位置,但它只是将该元素放置在容器元素的顶部。我做错了什么

   create: function(){

    console.log("cone created");

    var el =  document.createElement('div');
    el.classList.add('cone');

    this.container.appendChild(el);

    this.el = el;

    this.x = Math.random () * canvas.innerWidth + 'px';
    this.y = Math.random () * canvas.innerHeight + 'px';

    },
我假设“画布”不是真正的画布,它只是一个

在这种情况下,您需要做几件事:

  • 确保您的容器具有
    位置:相对
  • 确保容器的子容器具有
    位置:绝对
  • 添加
    el.style.left=this.x;el.style.top=this.y以实际定位元素

也许用内联css插入
div
可以处理这个问题

我写了一个样本:

$(document).ready(function() {
  var sqrPixel = 10;

  var posX = 30;
  var posY = 100;

  $('body').append('<div style="background: #ccc; box-shadow: 2px 2px 2px #000; position: absolute; width: ' + sqrPixel + 'px; height: ' + sqrPixel + 'px; left: ' + posX + '; top: ' + posY + ';"></div>');
});
$(文档).ready(函数(){
var sqrpix=10;
var-posX=30;
var-posY=100;
$('body')。追加('');
});
我将方块附加到
主体
。如果你想的话就换吧。您可以随机设置
posX
posY


我知道它看起来有点凌乱,但至少对我来说是有效的。

实际使用
this.x
this.y
的代码在哪里?