简体   繁体   English

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

[英]Reusable JavaScript Component: How to make it?

I would like to create a reusable JavaScript component out of the following canvas spinner. 我想从以下画布微调器中创建一个可重用的JavaScript组件。 Never done this before. 以前从未做过。 How to achieve it and how to use the component? 如何实现它以及如何使用组件?

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

HTML: HTML:

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

JS: 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);

EDIT - SOLUTION: 编辑-解决方案:

Here comes a solution if anybody is interested 如果有人感兴趣,这里有一个解决方案

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

There are any number of ways to do this. 有许多方法可以做到这一点。 Javascript is an object oriented language so you can easily write like: 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);
}

Now you can use this object like so: 现在您可以像下面这样使用该对象:

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

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

Basically, you are creating a class whose sole purpose in life is to draw a spinner on a canvas. 基本上,您正在创建一个类,其唯一的目的是在画布上绘制微调器。 In this example, you'll note that you're passing in the canvas's context into the object, since the details of the canvas itself is not relevant to this class's interest. 在此示例中,您将注意到您将画布的上下文传递给对象,因为画布本身的详细信息与此类的兴趣无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM