如何在HTML中使用JavaScript创建圆形,方形或三角形?

时间:2015-01-05 19:32:39

标签: javascript html css shapes

我是编码的新手,我试图在点击后随机创建三种不同的形状 - 圆形,正方形和三角形。我已经让我的代码随机创建一个圆形或正方形,但三角形总是在方形或圆形元素内,而不是自己。如何制作圆形,方形或三角形而不仅仅是一个内部有三角形的正方形或圆形?

<div id="shape1"></div>

CSS样式(我试图将三角形设置为“基本”形状。

#shape1 {
    width: 0;
    height: 0;
    border-left: 100px solid transparent;
    border-right: 100px solid transparent;
    border-bottom: 200px solid #2f2f2f;
    font-size: 0;
    line-height: 0;
}

main.js

setTimeout(function () {
        if (Math.random()<=0.3){
            document.getElementById("shape1").style.borderRadius="50%";
        }
        else if (Math.random()<=0.6){
            document.getElementById("shape1").style.borderRadius="0";
        }
        else {
            document.getElementById("shape1").style = this.self;
        }

非常感谢任何帮助。最好的编码给你。

3 个答案:

答案 0 :(得分:4)

您可以定义三个不同的CSS类 - 每个形状一个类。请注意,样式表中的类以点“。”开头。并使用class="..."属性应用于DOM元素。

在CSS文件中定义这四个CSS规则:

#shape1 {
    /* common styles for all shapes */
}

.square {
    /* square specific CSS */
}
.circle {
    /* circle specific CSS */
}
.triangle {
    /* triangle specific CSS */
}

您现在可以做的只是在元素上设置正确的类:

var shape = document.getElementById("shape1");

if (Math.random()<=0.3){
    shape.className = "square";
}
else if (Math.random()<=0.6){
    shape.className = "circle";
}
else {
    shape.className = "triangle";
}

我希望这是你想做的事情;)。

答案 1 :(得分:1)

您也可以使用svg

defs标签中定义形状,在点击事件中使用随机形状。

&#13;
&#13;
var shape = document.getElementById('shape');
var shapes = ['circle', 'square', 'triangle'];
shape.addEventListener('click', function() {
  shape.setAttributeNS('http://www.w3.org/1999/xlink', 'href', '#' + shapes[Math.floor(Math.random() * shapes.length)]);
})
&#13;
<svg width="200" height="200">
  <defs>
    <path id="circle" d="M0,100 a100,100 0 1,0 200,0 a100,100 0 1,0 -200,0" fill="rosybrown" />
    <path id="square" d="M0,0 h200 v200 h-200z" fill="tan" />
    <path id="triangle" d="M100,0 l100,200 h-200z" fill="teal" />
  </defs>
  <use id="shape" xlink:href="#circle" />
</svg>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你几乎得到了它。只需为每个形状应用所有边框属性。

<强>段:

&#13;
&#13;
setInterval(function () {
  var shape1= document.getElementById("shape1");
  if (Math.random()<=0.3){
    shape1.style.borderLeft= shape1.style.borderRight= shape1.style.borderBottom= shape1.style.borderTop= '100px solid';
    shape1.style.borderRadius="50%";
  }
  else if (Math.random()<=0.6){
    shape1.style.borderLeft= shape1.style.borderRight= shape1.style.borderBottom= shape1.style.borderTop= '100px solid';
    shape1.style.borderRadius="0";
  }
  else {
    shape1.style.borderLeft= shape1.style.borderRight= '100px solid transparent';
    shape1.style.borderBottom= '200px solid #2f2f2f';
    shape1.style.borderTop= '0';
    shape1.style.borderRadius="0";
  }
},500);
&#13;
#shape1 {
  width: 0px;
  height: 0px;
  font-size: 0;
  line-height: 0;
}
&#13;
<div id="shape1"></div>
&#13;
&#13;
&#13;