i want the user to be able to click somewhere on the canvas and the polygon will appear on it
<DIV id="canvasarea" class="rounded">
<CANVAS id="canvas" width="800px" height="800px开发者_开发百科"></CANVAS>
</DIV>
Use a javascript library, I'd try processingjs first - keep in mind IE has to be tricked into supporting canvas.
I didn't see a sample that matched your request exactly but these two should give you a good starting point
http://processingjs.org/learning/basic/shapeprimitives
same-domain-as-above/learning/topic/continuouslines
there is also a great primer on canvas here - google "dive into html5 canvas"
Here is a function I included in an object using mootools library. You could implement it in plain javascript too. ctx is equal to canvas.getContext('2d') object and n var defines the number of sides for the polygon we want... I hope you get the idea, the solution is requires only basic math.
polygonPath: function(ctx, n) {
var eq = 360 / n;
var radius = 50;
this.points = {xy: []};
ctx.beginPath();
ctx.moveTo(50,0);
for (var i = 0 ; i <= n; i++){
var deg = i * eq;
var rad = this.radConst * deg;
var x1 = radius * Math.cos(rad);
var y1 = radius * Math.sin(rad);
console.log('x: ' + x1 + ', y: ' + y1 + ', deg: ' + deg);
ctx.lineTo(x1,y1);
this.points.xy.push(x1 + ',' + y1 + ',' + rad);
}
ctx.stroke();
ctx.closePath();
/* Pentagon:
point 1 : 50,0
point 2: 15.45, 47.55
point 3: -40.45, 29.38
point 4: -40.45, -29.38
point 5: 15.45, -47.55
point 6 : 50, -1.22e-14*/
},
KineticJS is a great way to get started quickly. Here's an example that shows you how to draw a polygon on the canvas:
http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-polygon-tutorial/
Detect your click and then run the logic provided in the example.
From here: http://www.authorcode.com/draw-and-fill-a-polygon-and-triangle-in-html5/
You can use the lineTo() method:
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();
If you not want to fill the polygon use the stroke()
method in the place of fill()
Thanks.
精彩评论