如何通过JavaScript函数在HTML5画布上绘制多边形 [英] How can i draw polygons on an HTML5 canvas through a JavaScript function
本文介绍了如何通过JavaScript函数在HTML5画布上绘制多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望用户能够单击画布上的某个位置,并且多边形将出现在画布上
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>
推荐答案
这是我使用mootools库包含在对象中的函数.您也可以用普通的javascript实现它.ctx等于canvas.getContext('2d')对象,n var定义了我们想要的多边形的边数...我希望您能明白,解决方案只需要基本数学即可.
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*/
},
这篇关于如何通过JavaScript函数在HTML5画布上绘制多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文