HTML5 Canvas Roullete [英] HTML5 Canvas Roullete

查看:122
本文介绍了HTML5 Canvas Roullete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 http://jsfiddle.net/e7fwt4wb/ ! roullete旋转在html5画布中正常运行,当我调用方法旋转时,roullete被旋转并停止在我的数字数组的随机数中!如何调用传递参数的函数停止在我的数字数组的位置?

I have this http://jsfiddle.net/e7fwt4wb/! roullete spin in html5 canvas-functioning normally, when I call the method spin the roullete is rotated and stopped in a random number of my array of numbers! How can I call the function passing a parameter to stop at a position of my array of numbers?

<script type="text/javascript">
var colors = ["#336600", "#660000", "#000000", "#660000",
    "#000000", "#660000", "#000000", "#660000",
    "#000000", "#660000", "#000000", "#660000", "#000000", "#660000", "#000000"];
var numbers = ["0", "1", "8", "2",
    "9", "3", "10", "4",
    "11", "5", "12", "6", "13", "7", "14"];

var startAngle = 0;
var arc = Math.PI / 6;
var spinTimeout = null;

var spinArcStart = 10;
var spinTime = 0;
var spinTimeTotal = 0;

var ctx;

function drawRouletteWheel() {
    var canvas = document.getElementById("canvas");
    if (canvas.getContext) {
        var outsideRadius = 200;
        var textRadius = 160;
        var insideRadius = 125;

        ctx = canvas.getContext("2d");
        ctx.clearRect(0, 0, 500, 500);


        ctx.strokeStyle = "black";
        ctx.lineWidth = 2;
        ctx.font = 'bold 18px Helvetica, Arial';

        for (var i = 0; i < 12; i++) {
            var angle = startAngle + i * arc;
            ctx.fillStyle = colors[i];

            ctx.beginPath();
            ctx.arc(250, 250, outsideRadius, angle, angle + arc, false);
            ctx.arc(250, 250, insideRadius, angle + arc, angle, true);
            ctx.stroke();
            ctx.fill();

            ctx.save();
            ctx.shadowOffsetX = -1;
            ctx.shadowOffsetY = -1;
            ctx.shadowBlur = 0;
            ctx.shadowColor = "rgb(220,220,220)";
            ctx.fillStyle = "white";
            ctx.translate(250 + Math.cos(angle + arc / 2) * textRadius,
                    250 + Math.sin(angle + arc / 2) * textRadius);
            ctx.rotate(angle + arc / 2 + Math.PI / 2);
            var text = numbers[i];
            ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
            ctx.restore();
        }

        //Arrow
        ctx.fillStyle = "yellow";
        ctx.beginPath();
        ctx.moveTo(250 - 4, 250 - (outsideRadius + 5));
        ctx.lineTo(250 + 4, 250 - (outsideRadius + 5));
        ctx.lineTo(250 + 4, 250 - (outsideRadius - 5));
        ctx.lineTo(250 + 9, 250 - (outsideRadius - 5));
        ctx.lineTo(250 + 0, 250 - (outsideRadius - 13));
        ctx.lineTo(250 - 9, 250 - (outsideRadius - 5));
        ctx.lineTo(250 - 4, 250 - (outsideRadius - 5));
        ctx.lineTo(250 - 4, 250 - (outsideRadius + 5));
        ctx.fill();
    }
}

function spin() {
    spinAngleStart = Math.random() * 10 + 10;
    spinTime = 0;
    spinTimeTotal = Math.random() * 3 + 4 * 1500;
    rotateWheel();
}

function rotateWheel() {
    spinTime += 30;
    if (spinTime >= spinTimeTotal) {
        stopRotateWheel();
        return;
    }
    var spinAngle = spinAngleStart - easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
    startAngle += (spinAngle * Math.PI / 180);
    drawRouletteWheel();
    spinTimeout = setTimeout('rotateWheel()', 30);
}

function stopRotateWheel() {
    clearTimeout(spinTimeout);
    var degrees = startAngle * 180 / Math.PI + 90;
    var arcd = arc * 180 / Math.PI;
    var index = Math.floor((360 - degrees % 360) / arcd);
    ctx.save();
    ctx.font = 'bold 30px Helvetica, Arial';
    ctx.textAlign = "center";
    var text = numbers[index]
    ctx.fillStyle = colors[index];
    ctx.fillText("Rolled: " + text, 250 - ctx.measureText(text).width / 2, 250 + 10);
    ctx.restore();
}

function easeOut(t, b, c, d) {
    var ts = (t /= d) * t;
    var tc = ts * t;
    return b + c * (tc + -3 * ts + 3 * t);
}

drawRouletteWheel();
</script>


推荐答案

这是如何旋转你的车轮并停止在车轮上的所需数字。

要使用Penner的Easing方程旋转您的车轮,您需要定义这4个属性:

To spin your wheel using Penner's Easing equations, you need to define these 4 properties:


  • 动画当前经过的时间

  • 方向盘的起始角度

  • 将轮子旋转到所需数量所需的角度总变化

  • 动画的总持续时间

  • The current elapsed time of the animation
  • The beginning angle of the wheel
  • The total change in angle required to rotate the wheel to the desired number
  • The total duration of the animation

鉴于这4个属性,您可以应用其中一个缓动方程来计算动画期间随时的车轮角度:

Given these 4 properties you can apply one of the easing equations to calculate the wheels angle at any time during the animation:

// t: current time inside duration, 
// b: beginning value,
// c: total change from beginning value,
// d: total duration
function easeOutQuart(t, b, c, d){
    // return the current eased value based on the current time
    return -c * ((t=t/d-1)*t*t*t - 1) + b;
}

例如,假设你要旋转到数字9口袋而不是持续时间为2秒。然后这些属性值将适用:

For example, assume you want to rotate to the number-9 pocket over a duration of 2 seconds. Then these property values will apply:


  • 当前已用时间: 800ms (例如),

  • 方向盘的起始角度: 0弧度

  • 角度的总变化需要旋转到数字9: 3.6652弧度

  • 总持续时间: 2000ms

  • Current elapsed time: 800ms (for example),
  • Beginning angle of the wheel: 0 radians,
  • Total change in angle required to rotate to number-9: 3.6652 radians
  • Total duration: 2000ms,

你可以计算出800毫秒的车轮旋转角度,如下所示:

And you can calculate the eased angle of wheel rotation at 800ms like this:

easeOutQuart(800,0,3.6652,2000);

所需的Penner属性中有三个是givens,但旋转到-9所需的总变化计算如下:

Three of the required Penner properties are "givens" but the total change required to rotate to number-9 is calculated like this:

// "9" is element#4 in numbers[]
var indexOfNumber9 = 4;  

// calc what angle each number occupies in the circle
var angleSweepPerNumber = (Math.PI*2) / totalCountOfNumbersOnWheel;

// calc the change in angle required to rotate the wheel to number-9
var endingAngleAt9 = (Math.PI*2) - angleSweepPerNumber * (indexOfNumber9+1);

// the arrow is at the top of the wheel so rotate another -PI/2 (== -90 degrees)
endingAngleAt9 -= Math.PI/2;

// endingAngle is now at the leading edge of the wedge
// so rotate a bit further so the array is clearly inside wedge#9
endingAngleAt9 += Math.random()*angleSweepPerNumber;

以下是示例代码和演示:

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

var colors = ["#336600", "#660000", "#000000", "#660000",
              "#000000", "#660000", "#000000", "#660000",
              "#000000", "#660000", "#000000", "#660000", "#000000", "#660000", "#000000"];
var numbers = ["0", "1", "8", "2",
               "9", "3", "10", "4",
               "11", "5", "12", "6", "13", "7", "14"];
var pocketCount=12;
var cheatText=numbers[4];
$('#cheat').text('Stop on '+cheatText);

var cw=canvas.width=ch=canvas.height=500;
var cx=cw/2;
var cy=ch/2;

// wheel & arrow are used often so cache them
var wheelCanvas=drawRouletteWheel();
var arrow=drawArrow();

var wheel={
  cx:cw/2,
  cy:ch/2,
  radius:Math.min(cw,ch)/2-20,
  startAngle:0,
  endAngle:Math.PI*4+cheatingSpin(cheatText),
  totalSteps:360,
  currentStep:0,
}

drawAll(wheel);

$('#spin').click(function(){requestAnimationFrame(animate);$(this).hide()});


// funcs

function cheatingSpin(hit){
  var PI=Math.PI;
  var PI2=PI*2;
  var index=numbers.indexOf(cheatText);
  var pocketSweep=PI2/pocketCount;
  // cheatText not in numbers[]? -- then spin randomly
  if(index<0){return(PI2*2+Math.random()*PI2);}
  // if cheating, calc random endAngle inside desired number's pocket
  return((PI2-pocketSweep*(index+1))+Math.random()*pocketSweep-PI/2);
}

function animate(time){
  if(wheel.currentStep>wheel.totalSteps){return;}
  drawAll(wheel);
  wheel.currentStep++;
  requestAnimationFrame(animate);
}

function easing(w){
  var t=w.currentStep;
  var b=w.startAngle;
  var d=w.totalSteps;
  var c=w.endAngle-w.startAngle;
  // Penner's OutQuart
  return (-c*((t=t/d-1)*t*t*t-1)+b+w.startAngle);    
}

function drawAll(w){
  var angle=easing(w);
  ctx.clearRect(0,0,cw,ch);
  ctx.translate(cx,cy);
  ctx.rotate(angle);
  ctx.drawImage(wheelCanvas,-wheelCanvas.width/2,-wheelCanvas.height/2);
  ctx.rotate(-angle);
  ctx.translate(-cx,-cy);
  ctx.drawImage(arrow,cx-arrow.width/2,44);
}

function drawRouletteWheel() {
  var outsideRadius = 200;
  var textRadius = 160;
  var insideRadius = 125;
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");   
  canvas.width=canvas.height=outsideRadius*2+6;
  var x=outsideRadius+3;
  var y=outsideRadius+3;
  var arc = Math.PI / (pocketCount/2);
  ctx.strokeStyle = "black";
  ctx.lineWidth = 2;
  ctx.font = 'bold 18px Helvetica, Arial';
  // wheel
  for (var i = 0; i < pocketCount; i++) {
    var angle = i * arc;
    ctx.fillStyle = colors[i];
    ctx.beginPath();
    ctx.arc(x,y, outsideRadius, angle, angle + arc, false);
    ctx.arc(x,y, insideRadius, angle + arc, angle, true);
    ctx.stroke();
    ctx.fill();
    ctx.save();
    ctx.shadowOffsetX = -1;
    ctx.shadowOffsetY = -1;
    ctx.shadowBlur = 0;
    ctx.shadowColor = "rgb(220,220,220)";
    ctx.fillStyle = "white";
    ctx.translate(x+Math.cos(angle + arc / 2) * textRadius,
                  y+Math.sin(angle + arc / 2) * textRadius);
    ctx.rotate(angle + arc / 2 + Math.PI / 2);
    var text = numbers[i];
    ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
    ctx.restore();
  }
  //
  return(canvas);
}

function drawArrow(){
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");   
  canvas.width=18;
  canvas.height=18;
  //Arrow
  ctx.fillStyle = "yellow";
  ctx.beginPath();
  ctx.moveTo(5,0);
  ctx.lineTo(13,0);
  ctx.lineTo(13,10);
  ctx.lineTo(18,10);
  ctx.lineTo(9,18);
  ctx.lineTo(0,10);
  ctx.lineTo(5,10);
  ctx.lineTo(5,0);
  ctx.fill();
  return(canvas);
}

body{ background-color: ivory; }
#canvas{border:1px solid red; background:lightgray; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id=cheat>Stop on this number</span>
<button id=spin>Spin</button><br>
<canvas id="canvas" width=300 height=300></canvas>

这篇关于HTML5 Canvas Roullete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆