JavaScript Common Tools Function Summary (Browser Environment)

  • 2021-08-21 19:41:28
  • OfStack

Front-end business more commonly used JavaScript tool functions, browser environment commonly used, can be directly copied in the project to use. It is easy to consult, and this article will be continuously updated.

1. file to base64


/**
 * file Convert to base64
 * @param {*} file file Object 
 * @param {*} callback 
 */
export const fileToDataURL = (file, callback) => {
 let freader = new FileReader();
 freader.readAsDataURL(file);
 freader.onload = function (e) { callback(e.target.result); }
}

2. Converting an blob stream to an base64


/**
 * blob Stream to base64
 * @param {*} blob blob Object 
 * @param {*} callback 
 */
export const blobToDataURL = (blob, callback) => {
 let freader = new FileReader();
 freader.readAsDataURL(blob);
 freader.onload = function (e) { callback(e.target.result); }
}

3. base64 to blob


/**
 * base64 Convert to blob
 * @param {*} dataurl base64
 */
export const dataURLtoBlob = (dataurl) => {
 let arr = dataurl.split(','),
  mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]),
  n = bstr.length,
  u8arr = new Uint8Array(n);
 while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
 }
 return new Blob([u8arr], { type: mime });
}

4. The lower versions of base64 converted to file and IE are incompatible


/**
 *  Will base64 Convert to file,IE Low version incompatible 
 * @param {*} dataurl base64
 * @param {*} filename  Filename 
 */
export const dataURLtoFile = (dataurl, filename) => {
 let arr = dataurl.split(','),
  mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]),
  n = bstr.length,
  u8arr = new Uint8Array(n);
 while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
 }
 return new File([u8arr], filename, { type: mime });
}

5. Image url is converted to base64


/**
 *  Picture url Convert into base64
 * @param {*} url  Picture url
 * @param {*} callback 
 * @param {*} outputFormat  Picture format 
 */
export const imgUrlToDataURL = (url, callback, outputFormat) => {
  let canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    img = new Image;
  img.crossOrigin = 'Anonymous';
  img.src = url + "?timeStamp=" + new Date().getTime();
  img.onload = function () {
    canvas.height = img.height;
    canvas.width = img.width;
    // ctx.drawImage(img, 0, 0);
    ctx.drawImage(this, 0, 0, img.width, img.height);
    let dataURL = canvas.toDataURL(outputFormat || 'image/png');
    // callback.call(this, dataURL);
    callback && callback(dataURL)
    canvas = null;
  };
}

6. Get window dimensions


export function getViewportSize() {
 let w = 0;
 let h = 0;
 if (window.innerWidth) {
  w = window.innerWidth
  h = window.innerHeight
 } else if (document.body && document.body.clientWidth) {
  w = document.body.clientWidth
  h = document.body.clientHeight
 } else if (document.documentElement && document.documentElement.clientWidth) {
  w = document.documentElement.clientWidth
  h = document.documentElement.clientHeight
 }
 return { w, h }
}

7. Browser Environment Detection


const ua = window.navigator.userAgent.toLowerCase()

//  Whether it is WeChat 
export const isWx = () => ua.match(/MicroMessenger/i) == 'micromessenger'

//  Whether or not ipad
export const isIpad = () => ua.indexOf('ipad') > -1

//  Whether or not iphone
export const isIphone = () => ua.indexOf('iphone os') > -1

//  Whether or not uc
export const isUc = () => ua.indexOf('ucweb') > -1

//  Whether or not windows pc
export const isWindows = () => ua.indexOf('windows') > -1

//  Whether or not android
export const isAndroid = () => ua.indexOf('android') > -1 || ua.indexOf('adr') > -1

//  Whether or not ios
export const isIos = () => /(iphone|ipod|ipad|ios)/i.test(ua)

//  Whether or not qq Browser 
export const isQq = () => ua.indexOf('mqqbrowser') > -1 && ua.indexOf(' qq') < 0

//  Whether or not qq Built-in browser 
export const isQQInstalled = () => ua.indexOf(' qq') > -1 && ua.indexOf('mqqbrowser') < 0

8. Turn full screen on and off


//  Open full screen 
export function launchFullscreen(element) {
 element = element || document.documentElement
 if (element.requestFullscreen) {
  element.requestFullscreen()
 } else if (element.mozRequestFullScreen) {
  element.mozRequestFullScreen()
 } else if (element.msRequestFullscreen) {
  element.msRequestFullscreen()
 } else if (element.webkitRequestFullscreen) {
  element.webkitRequestFullScreen()
 }
}

//  Turn off full screen 
export function exitFullscreen() {
 if (document.exitFullscreen) {
  document.exitFullscreen()
 } else if (document.msExitFullscreen) {
  document.msExitFullscreen()
 } else if (document.mozCancelFullScreen) {
  document.mozCancelFullScreen()
 } else if (document.webkitExitFullscreen) {
  document.webkitExitFullscreen()
 }
}

9. Return to the top/specified position for scrolling animation


/**
 * @param {*} number  Distance from the top of the page 
 * @param {*} time  Time required for scrolling   Unit ms
 */
const scrolling = (number = 0, time) => {
  if (!time) {
    document.body.scrollTop = document.documentElement.scrollTop = number;
    return number;
  }
  //  Set the interval between loops   The smaller the value, the higher the consumption performance 
  const spacingTime = 20;
  //  Count the number of cycles 
  let spacingInex = time / spacingTime; 
  //  Gets the current scroll bar position 
  let nowTop = document.body.scrollTop + document.documentElement.scrollTop; 
  //  Calculate the distance of each slide 
  let everTop = (number - nowTop) / spacingInex;

  let scrollTimer = setInterval(() => {
    if (spacingInex > 0) {
      spacingInex--;
      ScrollTop(nowTop += everTop);
    } else {
      clearInterval(scrollTimer); //  Clear the timer 
    }
  }, spacingTime);
};

//  Scroll to the top of the distance page 500px Location of   Animation time is 300ms
// scrolling(500, 300);

10. Realize anchor point scrolling


//  Used H5 Adj. scrollIntoView Method, which is 1 The function in the experiment, IE 8 Below, Safari 6 Below, Safari on iOS 5 The following are incompatible 
const scrollToAnchor = (anchorName) => {
  if (anchorName) {
    //  Find the anchor point 
    let anchorElement = document.getElementById(anchorName);
    //  If corresponding id If the anchor point exists, jump to the anchor point 
    if (anchorElement) {
      anchorElement.scrollIntoView({
        behavior: 'auto', //  Define animation transition effects,  "auto" Or  "smooth"  Yeah 1 . Default to  "auto"
        block: 'start', //  Defines vertical alignment,  "start", "center", "end",  Or  "nearest" Yeah 1 . Default to  "start"
        inline: 'nearest', //  Defines horizontal alignment,  "start", "center", "end",  Or  "nearest" Yeah 1 . Default to  "nearest"
      });
    }
  }
}

The above is JavaScript commonly used tool function summary (browser environment) details, more information about JavaScript tool function please pay attention to other related articles on this site!


Related articles: