2011-01-29 32 views

Respuesta

126

Crear un camino con moveTo y lineTo (live demo):

var ctx = canvas.getContext('2d'); 
ctx.fillStyle = '#f00'; 
ctx.beginPath(); 
ctx.moveTo(0, 0); 
ctx.lineTo(100,50); 
ctx.lineTo(50, 100); 
ctx.lineTo(0, 90); 
ctx.closePath(); 
ctx.fill(); 
+2

+1, no tenía idea de jsFiddle compatibles con lienzos HTML5. –

+90

@Gio Borje: AFAIK, jsFiddle no se preocupa por el lienzo, ese es su navegador. jsFiddle solo le devuelve su HTML/CSS/JS. –

+0

Excelente solución. Código muy limpio. gracias @phihag. Algo que puedo entender! – sparkle

29
//poly [x,y, x,y, x,y.....]; 
var poly=[ 5,5, 100,50, 50,100, 10,90 ]; 
var canvas=document.getElementById("canvas") 
var ctx = canvas.getContext('2d'); 
ctx.fillStyle = '#f00'; 

ctx.beginPath(); 
ctx.moveTo(poly[0], poly[1]); 
for(item=2 ; item < poly.length-1 ; item+=2){ctx.lineTo(poly[item] , poly[item+1])} 

ctx.closePath(); 
ctx.fill(); 
+0

Es por eso que desearía poder entender fundamentalmente el método JavaScript 'for' de vainilla. Esa única línea de código simplificó mucho las cosas. Normalmente utilizo jQuery '.each()' pero su aplicación es mucho menos versátil. –

+2

@AlexanderDixon El javascript anterior no es realmente un buen ejemplo.* Todas las variables * necesitan 'var', en el código anterior' item' está contaminando el espacio de nombres global. Todo está en una línea, lo que reduce la legibilidad. Si no te importa la legibilidad, entonces también podrías quitar las llaves. – Annan

24

de http://www.scienceprimer.com/drawing-regular-polygons-javascript-canvas:

el siguiente código dibuja un hexágono. Cambie el número de lados para crear diferentes polígonos regulares.

// hexagon 
var numberOfSides = 6, 
    size = 20, 
    Xcenter = 25, 
    Ycenter = 25; 

cxt.beginPath(); 
cxt.moveTo (Xcenter + size * Math.cos(0), Ycenter + size * Math.sin(0));   

for (var i = 1; i <= numberOfSides;i += 1) { 
    cxt.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI/numberOfSides), Ycenter + size * Math.sin(i * 2 * Math.PI/numberOfSides)); 
} 

cxt.strokeStyle = "#000000"; 
cxt.lineWidth = 1; 
cxt.stroke(); 
+2

Esto era grande, muy elegante, también, si se agrega: ' cxt.save();' ' cxt.fillStyle = "#"; FF000' ' cxt.fill();' ' cxt.restore (); ' Puede completar la forma. – samuelkobe

+0

esto es genial - he estado jugando jugando con él, pero no puedo entender cómo podría rotar el polígono elegido - ¿alguna idea? – eskimomatt

+1

Hay algunas maneras de obtener lo que desea. Una opción es usar el método built in cxt.rotate() [junto con cxt.save() y cxt.restore()] para rotar partes del lienzo. Alternativamente, agregar un valor constante a las funciones cos y sin también funcionará. Vea este jsfiddle para una demostración: http://jsfiddle.net/kwyhn3ba/ –

1

Se puede utilizar el método lineTo() mismo que: var objctx = canvas.getContext ('2d');

 objctx.beginPath(); 
     objctx.moveTo(75, 50); 
     objctx.lineTo(175, 50); 
     objctx.lineTo(200, 75); 
     objctx.lineTo(175, 100); 
     objctx.lineTo(75, 100); 
     objctx.lineTo(50, 75); 
     objctx.closePath(); 
     objctx.fillStyle = "rgb(200,0,0)"; 
     objctx.fill(); 

si no desea llenar el polígono utilizar el método de accidente cerebrovascular() en el lugar de llenado()

También puede comprobar lo siguiente: http://www.authorcode.com/draw-and-fill-a-polygon-and-triangle-in-html5/

gracias

7
//create and fill polygon 
CanvasRenderingContext2D.prototype.fillPolygon = function (pointsArray, fillColor,  strokeColor) { 
    if (pointsArray.length <= 0) return; 
    this.moveTo(pointsArray[0][0], pointsArray[0][1]); 
    for (var i = 0; i < pointsArray.length; i++) { 
     this.lineTo(pointsArray[i][0], pointsArray[i][1]); 
    } 
    if (strokeColor != null && strokeColor != undefined) 
     this.strokeStyle = strokeColor; 

    if (fillColor != null && fillColor != undefined) { 
     this.fillStyle = fillColor; 
     this.fill(); 
    } 
} 
//And you can use this method as 
var polygonPoints = [[10,100],[20,75],[50,100],[100,100],[10,100]]; 
context.fillPolygon(polygonPoints, '#F00','#000'); 
3

Aquí hay una función que incluso admite el dibujo en sentido horario/antihorario que usted controla rellena con la regla de bobinado distinto de cero.

Here is a full article on how it works and more.

// Defines a path for any regular polygon with the specified number of sides and radius, 
// centered on the provide x and y coordinates. 
// optional parameters: startAngle and anticlockwise 

function polygon(ctx, x, y, radius, sides, startAngle, anticlockwise) { 
    if (sides < 3) return; 
    var a = (Math.PI * 2)/sides; 
    a = anticlockwise?-a:a; 
    ctx.save(); 
    ctx.translate(x,y); 
    ctx.rotate(startAngle); 
    ctx.moveTo(radius,0); 
    for (var i = 1; i < sides; i++) { 
    ctx.lineTo(radius*Math.cos(a*i),radius*Math.sin(a*i)); 
    } 
    ctx.closePath(); 
    ctx.restore(); 
} 

// Example using the function. 
// Define a path in the shape of a pentagon and then fill and stroke it. 
context.beginPath(); 
polygon(context,125,125,100,5,-Math.PI/2); 
context.fillStyle="rgba(227,11,93,0.75)"; 
context.fill(); 
context.stroke(); 
+0

Ese artículo es bastante largo para decir "dibujando un círculo con menos bordes". Es posible que desee almacenar en caché los resultados para evitar llamar tanto a cos y a tanto (perdóneme si ya lo está haciendo, no soy un programador de JavaScript). – QuantumKarl

1

Además de @canvastag, utilizar un bucle while con shift Creo que es más concisa:

var canvas = document.getElementById('canvas'); 
var ctx = canvas.getContext('2d'); 

var poly = [5, 5, 100, 50, 50, 100, 10, 90]; 

// copy array 
var shape = poly.slice(0); 

ctx.fillStyle = '#f00' 
ctx.beginPath(); 
ctx.moveTo(shape.shift(), shape.shift()); 
while(shape.length) { 
    ctx.lineTo(shape.shift(), shape.shift()); 
} 
ctx.closePath(); 
ctx.fill(); 
0

Para hacer un hexágono simple sin la necesidad de un bucle, Justo use la función beginPath(). Asegúrese de que canvas.getContext ('2d') sea igual a ctx, de lo contrario, no funcionará.

También me gusta agregar una variable llamada veces que puedo usar para escalar el objeto si es necesario. Esto es lo que no necesito cambiar cada número.

 // Times Variable 

    var times = 1; 

    // Create a shape 

    ctx.beginPath(); 
    ctx.moveTo(99*times, 0*times); 
    ctx.lineTo(99*times, 0*times); 
    ctx.lineTo(198*times, 50*times); 
    ctx.lineTo(198*times, 148*times); 
    ctx.lineTo(99*times, 198*times); 
    ctx.lineTo(99*times, 198*times); 
    ctx.lineTo(1*times, 148*times); 
    ctx.lineTo(1*times,57*times); 
    ctx.closePath(); 
    ctx.clip(); 
    ctx.stroke(); 
Cuestiones relacionadas