$(function() {
let miLienzo = document.getElementById("myCanvas");
let lapiz = miLienzo.getContext("2d");
let cw = (miLienzo.width = 300),
cx = cw / 2;
let ch = (miLienzo.height = 200),
cy = ch / 2;
let R = 40;
$("#Figuras").on("change", function() {
pintarFigura($(this).val(), lapiz);
});
function pintarFigura(lados, ctx) {
clearCanvas();
ctx.save();
ctx.translate(cx,cy);
if(lados != "rect"){
dibujarPoligono(lados, ctx);
}else{
dibujarRectangulo(ctx,100,50)
}
ctx.restore();
}
function clearCanvas() {
let miLienzo = document.getElementById("myCanvas");
let lapiz = miLienzo.getContext("2d");
lapiz.clearRect(-miLienzo.width, -miLienzo.height, 2*miLienzo.width, 2*miLienzo.height);
lapiz.beginPath();
}
function dibujarPoligono(L, ctx) {
ctx.beginPath();
for (var i = 0; i < L; i++) {
x = R * Math.cos((2 * Math.PI / L * i)-Math.PI/2);
y = R * Math.sin((2 * Math.PI / L * i)-Math.PI/2);
ctx.lineTo(x, y);
}
ctx.closePath();
ctx.stroke();
}
function dibujarRectangulo(ctx,w,h){
ctx.beginPath();
ctx.strokeRect(-w/2,-h/2,w,h);
}
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Open sans';
width:100vw;
height:100vh;
}
.contenedor{
width:308px;
height:270px;
display:block;
position:absolute;
margin:auto;
top:0;bottom:0;left:0;right:0;
text-align:center;
}
p{margin:1em;}
canvas{border:4px solid black;}
#Figuras{
font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contenedor">
<p><select id="Figuras">
<option>
-----
</option>
<option value="100">
Círculo
</option>
<option value="3">
Triángulo
</option>
<option value="4">
Cuadrado
</option>
<option value="rect">
rect
</option>
<option value="5">
Pentágono
</option>
<option value="6">
Hexágono
</option>
<option value="8">
Octágono
</option>
</select></p>
<canvas id="myCanvas" style="" >
</canvas>
</div>