我一直在使用HTML 5编写一个简单的算盘实现形式here,但我在查找获胜者细分时遇到了一些问题,这里是JSFiddle中的代码:
http://jsfiddle.net/bramp/94jP6/
JSFiddle中的重要功能:
// Called when segments have changed
update: function() {
// Ensure we start mid way on a item
//var r = Math.floor(Math.random() * wheel.segments.length);
var r = 0;
wheel.angleCurrent = ((r + 0.5) / wheel.segments.length) * Math.PI * 2;
var segments = wheel.segments;
var len = segments.length;
var colors = wheel.colors;
var colorLen = colors.length;
// Generate a color cache (so we have consistant coloring)
var seg_color = new Array();
for (var i = 0; i < len; i++)
seg_color.push(colors[segments[i].hashCode().mod(colorLen)]);
wheel.seg_color = seg_color;
wheel.draw();
}
和
drawNeedle: function() {
var ctx = wheel.canvasContext;
var centerX = wheel.centerX;
var centerY = wheel.centerY;
var size = wheel.size;
ctx.lineWidth = 1;
ctx.strokeStyle = '#000000';
ctx.fileStyle = '#ffffff';
ctx.beginPath();
ctx.moveTo(centerX + size - 40, centerY);
ctx.lineTo(centerX + size + 20, centerY - 10);
ctx.lineTo(centerX + size + 20, centerY + 10);
ctx.closePath();
ctx.stroke();
ctx.fill();
// Which segment is being pointed to?
var i = wheel.segments.length - Math.floor((wheel.angleCurrent / (Math.PI * 2)) * wheel.segments.length) - 1;
// Now draw the winning name
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillStyle = '#000000';
ctx.font = "2em Arial";
ctx.fillText(wheel.segments[i], centerX + size + 25, centerY);
},
第256行中的是当前代码获胜的地方:
var i = wheel.segments.length - Math.floor((wheel.angleCurrent / (Math.PI * 2)) * wheel.segments.length) - 1;
但是在车轮的右侧,我试图让它作为赢家点在顶部。我长期以来一直在努力,感谢你的帮助或指导。谢谢
答案 0 :(得分:3)
Here is a working solution Fiddle 。解释如下:
首先我们需要在方向盘顶部绘制指向正确位置的指针:
drawNeedle: function() {
...
ctx.beginPath();
ctx.moveTo(centerX + 20, centerY - size - 20);
ctx.lineTo(centerX - 20, centerY - size - 20);
ctx.lineTo(centerX , centerY - size + 20);
ctx.closePath();
...
}
在此处您已给出的代码段中:
var i = wheel.segments.length - Math.floor((wheel.angleCurrent / (Math.PI * 2)) * wheel.segments.length) - 1;
wheel.angleCurrent / (Math.PI * 2)
部分表示它位于右侧。请注意,在JavaScript中,我们开始使用“单位圆”。要解决此问题,我们只需要将角度偏移90度(或者在我们的例子中以弧度为单位添加Math.PI/2
):
var change = wheel.angleCurrent + (Math.PI/2);
var i = wheel.segments.length - Math.floor((change / ( Math.PI * 2)) * wheel.segments.length) - 1;
if(i < 0) i = i + 17; // 17 = wheel.segments.length
计算i
的方式取决于我们从右侧开始。当我们从-5 to 12
以外的0 to 16
进行更改时,它会抵消一些项目。要在负项目(我们的偏移项目)上修复它,我们只需将它们添加为13到16.在其他单词中添加17(与wheel.segments.length
相同)。