use

The use here takes the introduction separately as an example,Global introductionUse similar.

WebLoading

Whether it is DOM, FULL or MINI , it will eventually go to WebLoading.

import type { LoadingType } from "web-loading";
import { initLoading } from 'web-loading'
let webLoading:LoadingType = initLoading({})
console.log(webLoading)

LoadingTypeloadingresizecloseupdategetOptionsgetLoadingId

loading

Start the animationloading

  • Parameters:

    • dom:HTMLElement
    • options?:OptionsType
  • Return: void

When the loading function is called, it will first check whether the loadingId exists (whether it is still being drawn). Only when there is no drawing status can it be started.

The loading parameter 2 can override the options of the initialization initLoading .

resize

Recalculate and draw the loading size.

  • Parameter: None
  • Return: void

Resizewill retrieve the size and redraw from the boundHtmlElement. This function will not re-instanceWebLoadingandloadingbusiness scenarios. For example, window. addEventListener (resize, loading. resize) may be used.

close

closeloading。

  • Parameter: None
  • Return: void

close will first clear all stores and other records ofWebLoading, and stop therequestAnimationFramecall, and finally clear the relevant elements according todelayInto. During the closing process,WebLoadingwill usehookCallto trigger thehookto close hook function (BEFORE _COLSE: before closing,COLSED: after closing, that is, after clearing the elements) to facilitate the drawing of model.

update

Draw model dynamically. Public Configuration cannot be modified dynamically.

  • Parameter:
    • options?:OptionsType
  • Return:void

The update function does not re-instance WebLoading, and re-drawsmodelthrough the parameter options. The business scenario is similar to loading, but loading initializesWebLoadingevery time. Only when it is closed can the corresponding business be implemented. Therefore,updateis recommended in the dynamic renderingmodelbusiness scenario.

getOptions

Get the current options configuration.

  • Parameter: None

  • Return:

    • options:OptionsType

getLoadingId

obtain loadingId

  • Parameter: None

  • Return:

    • loadingId:string | null

The loadingId will be assigned a value after initialization, and will be assigned a value ofnullaftercloseis closed. Therefore, ifloadingIdis null, there is currently no drawing status, otherwise the opposite is true.

options

import { initLoading, MODEL_TYPES } from "web-loading";
let webLoading = initLoading({
    model:MODEL_TYPES.GEAR
})

Public

attributetypedefaultremarks
html?:string''**Html ** loading method (priority is higher than custom)
custom?:typeof BaseModel or nullnullCustom model (has the highest priority)
type?:LOADING_TYPESLOADING_TYPES.DOMStart mode
extendClass?:string or null or undefinedextendStart byMINIorFILLisclass
model?:MODEL_TYPESMODEL_TYPES.RINGModel module
text?:string加载中...Font content
textGap?:number8Font spacing
fontSize?:number12Font size
fontFamily?:stringMicrosoft YaHeiFont type
delay?:number65Animation delay
delayInto?:number320Turn enter/off animation delay
notFeelnumber0Senseless refresh (calling close without drawing loading within 300:300 milliseconds)
optimization?:booleanfalseOptimization processing (not supported temporarily)
zIndex?:string2001Loading level
themeColor?:stringrgba(64,158,255,1)Theme color
bgColor?:stringrgba(0, 0, 0, 0.8)Background color
shadowColor?:stringrgba(64,158,255,0.6)Shadow color
shadowOffsetX?:number2Shadow X
shadowOffsetY?:number2Shadow Y
shadowBlur?:number5Shadow range
pointerEvents?:booleanfalseEvent penetration(DOMmodel)
toast?:booleantrueWhether to display a prompt
  • LOADING_TYPES
attributeenumremarks
DOMdomElement
FULLfullFull screen
MINIminiMobile terminal
  • MODEL_TYPES

Supported models

model

Model configuration details

custom model

TypeScript Item Example

  • custom
import type { OptionsType, LimitType, ElementType } from "web-loading";
import { BaseModel } from "web-loading";
// 1?.If options in the model need custom parameters, define options type
interface CustomOptionsType extends OptionsType {
  size?: number;
}
// 2?.Customize the default parameters of the model (if you do not need to customize the options parameter, you can use OptionsType)
// 2.1?. Define default values
let modelDefOptions: CustomOptionsType = {
  size: 10,
};
// 2.2?.Size of limit value
let limits: Array<LimitType> = [
  {
    key: "size",
    message: "key < 100",
    limit: (key) => {
      return key < 100;
    },
  },
];
// 3.Custom model class
class CustomLoading extends BaseModel<CustomOptionsType> {
  constructor(w: number, h: number, canvas: HTMLCanvasElement, options: Required<CustomOptionsType>, element: ElementType) {
   super(w, h, canvas, options, element, modelDefOptions, limits, function modelDefCall(model) {
      //BaseModel initialization success callback (you can do some special initialization operations yourself)
      //The model is CustomLoading itself. Here, the initialization default brush fill is red
      model.ctx.fillStyle = "red";
    });
    // 根据周期调用
    this.run(this.draw);
  }
  draw() {
    // Empty the canvas
    this.clearRect();
    let op = this.options;
    // Draw (get the configured custom options parameter here)
    this.ctx.fillRect(-op.size / 2, -op.size / 2, op.size, op.size);
  }
}

Here is a simple custom drawing of a rectangle

  • BaseModel is a user-defined inheritance class. If it is introduced globally, the BaseModel attribute is mounted in the window.
  • Note: modelDefOptions, limits, modelDefCall are not required parameters
  • Here, if the customized model does not need the options parameter, you can omit the 1、2 steps.
  • loading
import type { LoadingType, CustomOptionsType } from "web-loading";
import { initLoading, BaseModel } from 'web-loading'
let dom = document.querySelector("xxx");
// configuration parameter
let options: CustomOptionsType = {
  custom: CustomLoading as typeof BaseModel,
  size: 20,
};
let webLoading: LoadingType = initLoading(options);
webLoading.loading(dom);

Native html project example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>web-loading</title>
  </head>
  <script src="https://cdn.jsdelivr.net/npm/web-loading"></script>
  <body>
    <div id="app">
      <div class="item">
        <div>
          id:
          <span class="value">001</span>
        </div>
        <div>
          user:
          <span class="value">use1</span>
        </div>
      </div>
    </div>
    <script>
      window.onload = () => {
        // encapsulation
        let modelDefOptions = {
          size: 10
        }
        let limits = [
          {
            key: 'size',
            message: 'key < 100',
            limit: (key) => {
              return key < 100
            }
          }
        ]
        class CustomLoading extends BaseModel {
          constructor(w, h, canvas, options, store) {
            super(w, h, canvas, options, store, modelDefOptions, function modelDefCall(model) {
              model.ctx.fillStyle = 'red'
            })
            this.run(this.draw)
          }
          draw() {
            this.clearRect()
            let op = this.options
            this.ctx.fillRect(-op.size / 2, -op.size / 2, op.size, op.size)
          }
        }
        // loading
        let docApp = document.querySelector('#app')
        const webLoading = initLoading({
          custom: CustomLoading,
          size: 20
        })
        window.addEventListener('resize', webLoading.resize)
        webLoading.loading(docApp)
        setTimeout(() => {
          webLoading.close()
        }, 1500)
      }
    </script>
  </body>
  <style>
    #app {
      margin: 12px;
      padding: 12px;
      height: 200px;
      border: 1px solid gray;
      overflow: auto;
      border-radius: 5px;
    }
    #app .item {
      display: flex;
      flex-direction: column;
      border: 1px solid gray;
      border-radius: 5px;
      padding: 10px;
      line-height: 30px;
      margin-bottom: 6px;
      height: 60px;
    }
    #app .item .value {
      display: inline-block;
      min-width: 31px;
      min-height: 16px;
      font-weight: bold;
      color: rgb(64, 158, 255);
    }
  </style>
</html>

1、BaseModelparameter

WebLoading will automatically inject relevant parameters when callingcustom.

parametertyperemarks
wnumberCanvas Width
hnumberCanvas height
canvasHTMLCanvasElementCanvas element, BaseModel default and get the context of 2d, but you can also get other contexts according to the canvas element
optionsRequired<CustomOptionsType>Options is to adjust model parameters, which are divided into public parameters and model parameters, which will be merged eventually, and Required indicates you The parameter of is not empty (has initial value)
elementElementTypeContainer element
modelDefOptions?:TCustom default parameters for model(optional)
limits?:Array<LimitType>Custom model's' options 'value restriction function (optional)
modelDefCall?:(model: BaseModel<T>) => voidBaseModel initialization completion callback (optional)

ElementType

InheritedHTMLElement

attributetyperemarks
loadingIdstring or nullRecord loading element id
$storeElementStoreTypeloding cache content
HTMLElement attribute.........

ElementType.$store:ElementStoreType

When drawing model, you need to use some states of WebLoading.

attributetyperemarks
optionsOptionsTypeSave the final merged options parameter
animationIdnumber or undefinedRecord animation status
loadingIdstring or nullRecord loading element id
hookCallHooksCallTypeHook function of loading
modelBaseModel or nullmodel in use

ElementType.$store.hookCall:HooksCallType

WebLoadingThe hook function triggered when closing.

HOOKSCALL_KEYEnumeration.

attributeenumtyperemarks
BEFORE_COLSEbeforeColseFunctionBefore closing
COLSEDcolsedFunctionAfter closing (after deleting elements)

Take custom as an example

// Other codes are omitted
class CustomLoading extends BaseModel<CustomOptionsType> {
    constructor(w: number, h: number, canvas: HTMLCanvasElement, options: Required<CustomOptionsType>, element: ElementType) {
        super(w, h, canvas, options, element);
        this.initOptions(defOptions);
        this.run(this.draw);
        this.store.hookCall.beforeColse(() => {
            console.log("Before closing");
        });
        this.store.hookCall.colsed(() => {
            console.log("After closing");
        });
    }
    draw() {
        let op = this.options;
        this.ctx.fillRect(0, 0, op.size, op.size);
    }
}

LimitType

Limit the range of options parameter values.

attributetyperemarks
keystringThe options attribute that needs to be restricted
messagestringPrompt for exceeding the limit
limit(key: any) => booleanRestricted operation

2、BaseModel function

BaseModelThe built-in function is mainly for user extension model rendering

functionreturnremarks
initContextCallvoidinitContextCall
runvoidrun
clearRectvoidclearRect
drowRadiusRectvoiddrowRadiusRect
drawTextvoiddrawText
clearAnimationFramevoidclearAnimationFrame

BaseModel:initContextCall

BaseModel Initialize the custom canvas property (triggered during inheritance).

参数类型备注
modelDefOptions?:TCustomize the default options value of model.
limits?:Array<LimitType>Customize the limit range of the options value of model.
modelDefCall?:BaseModel<T>BaseModel initialization completion callback.

BaseModel:run

The requestAnimationFrame is delayed according to the options.delay.

parametertyperemarks
funFunctionIf it is loading before calling, the last state will be cleared.
this.run(()=>{
    // Triggered according to options.delay
})

BaseModel:clearRect

Empty the canvas.

parametertyperemarks
x?:numberEmpty starting point X
y?:numberEmpty starting point Y
w_r?:numberEmpty end X (width), in case of circular emptying w_ R is radius
h?:numberEmpty end Y (height)
  • Empty all
this.clearRect()

Considering that the drawing area may exceed the default width and height, emptying all will empty twice the width and height.

  • Custom Emptying
this.clearRect(0,0,100,100)

Emptying starts at the coordinates of x=0, y=0 and ends at x=100, y=100.

  • Empty circular area
this.clearRect(0,0,10)

Empty the area with x=0, y=0 and radius of 10.

BaseModel:drowRadiusRect

Draw a rectangle with rounded corners.

parametertyperemarks
xnumberStart X
ynumberStart Y
wnumberEnd X (width)
hnumberEnd Y (height)
this.drowRadiusRect(0, 0, 100, 100, 10)
// Need to draw by yourself
this.ctx.fill()

Draw a rectangle with x=0, y=0 width and height of 100 and rounded corners of 10.

BaseModel:drawText

Draw default text.

parametertyperemarks
params?:DrawTextParamsTypeDraw text parameters

BaseModel:drawText.DrawTextParamsType

parametertypedefaultremarks
esGapnumber0Extra text gap (textGap+fontSize)
xnumber0X-axis
textstring加载中...text
textColorstringrgba(64,158,255,1)text color
this.drawText()

BaseModel:clearAnimationFrame

Empty (stop)requestAnimationFrame

parametertyperemarks
idnumberanimationId
this.clearAnimationFrame(element.$store.animationId)

The ID passed in is id returned by requestAnimationFrame , and WebLoading has been saved in the store.

3、BaseModel technique

Dynamic options

Whether it is initialization or in the run function, modifying options is real-time and dynamic, which can control the delay time triggered byrequestAnimationFrameto be irregular.

this.run(()=>{
    // Dynamic modification of delay will affect the trigger of run function
    this.options.delay = 10
})

Html configuration method

Add html configuration to options, which has priority over model and custom.

initialization

import { initLoading } from 'web-loading'
let webLoading = initLoading({
    html:`<div class="spinner">
    <svg viewBox="25 25 50 50" class="circular">
        <circle stroke-miterlimit="10" stroke-width="3" fill="none" r="20" cy="50" cx="50" class="path"></circle>
    </svg>
</div>`
})

Html priority is higher than custom.

Css animation

.spinner {
  --red: #d62d20;
  --blue: #0057e7;
  --green: #008744;
  --yellow: #ffa700;
  position: relative;
  width: 60px;
}

.spinner:before {
  content: "";
  display: block;
  padding-top: 100%;
}

.circular {
  animation: rotate73451 2s linear infinite;
  height: 100%;
  transform-origin: center center;
  width: 100%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

.path {
  stroke-dasharray: 1, 200;
  stroke-dashoffset: 0;
  animation: dash0175 1.5s ease-in-out infinite, color7123 6s ease-in-out infinite;
  stroke-linecap: round;
}

@keyframes rotate73451 {
  100% {
    transform: rotate(360deg);
  }
}

@keyframes dash0175 {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }

  50% {
    stroke-dasharray: 89, 200;
    stroke-dashoffset: -35px;
  }

  100% {
    stroke-dasharray: 89, 200;
    stroke-dashoffset: -124px;
  }
}

@keyframes color7123 {
  100%, 0% {
    stroke: var(--red);
  }

  40% {
    stroke: var(--blue);
  }

  66% {
    stroke: var(--green);
  }

  80%, 90% {
    stroke: var(--yellow);
  }
}

The class naming should try to isolate external elements.

Last Updated:
Contributors: tommyrunner