【问题标题】:Reusable JavaScript Component: How to make it?可重用的 JavaScript 组件:如何制作?
【发布时间】:2014-10-05 00:23:56
【问题描述】:

我想从以下画布微调器中创建一个可重用的 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 user-interface canvas components


    【解决方案1】:

    有很多方法可以做到这一点。 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();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2017-05-27
      • 2021-12-21
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多