可重用的JavaScript组件:如何制作?

非常好奇

我想从以下画布微调器中创建一个可重用的JavaScript组件。以前从未做过。如何实现它以及如何使用组件?

http://codepen.io/anon/pen/tkpqc

HTML:

<canvas id="spinner"></canvas>

JS:

 var canvas = document.getElementById('spinner');
    var context = canvas.getContext('2d');
    var start = new Date();
    var lines = 8,  
        cW = context.canvas.width,
        cH = context.canvas.height;
        centerX = canvas.width / 2;
        centerY = canvas.height / 2;
        radius = 20;

    var draw = function() {
        var rotation = parseInt(((new Date() - start) / 1000) * lines) % lines;
        context.save();
        context.clearRect(0, 0, cW, cH);

      for (var i = 0; i < lines; i++) {
            context.beginPath();
            //context.rotate(Math.PI * 2 / lines);
        var rot = 2*Math.PI/lines;
        var space = 2*Math.PI/(lines * 12);
        context.arc(centerX,centerY,radius,rot * (i) + space,rot * (i+1) - space);
          if (i == rotation)
            context.strokeStyle="#ED3000";
          else 
            context.strokeStyle="#CDCDCD";
            context.lineWidth=10;
            context.stroke();
        }

        context.restore();
    };
    window.setInterval(draw, 1000 / 30);

编辑-解决方案:

如果有人感兴趣,这里有一个解决方案

http://codepen.io/anon/pen/tkpqc

亚历克斯·道

有许多方法可以做到这一点。Javascript是一种面向对象的语言,因此您可以轻松地编写如下代码:

var Spinner = function(canvas_context) 
{
    this.context = canvas_context;
    // Whatever other properties you needed to create
    this.timer = false;

}

Spinner.prototype.draw = function()
{
    // Draw spinner
}

Spinner.prototype.start = function()
{
    this.timer = setInterval(this.start, 1000 / 30);
}

Spinner.prototype.stop = function() {
    clearInterval(this.timer);
}

现在,您可以像下面这样使用该对象:

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

var spinner = new Spinner(context);
spinner.start();

基本上,您正在创建一个类,其唯一的目的是在画布上绘制微调器。在此示例中,您将注意到您将画布的上下文传递到对象中,因为画布本身的详细信息与此类的兴趣无关。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章