js 使用 canvas 实现一个一笔一画写汉字的效果 All In One


js 使用 canvas 实现一个一笔一画写汉字的效果 All In One

js canvas 实现按照笔画手绘汉字效果

canvas 画字

fillText & setTimeout & requestAnimationFrame

solution ?




  
  
  
  
  
  js 使用 canvas 实现一个一笔一画写汉字的效果 All In One
  
  


  

js 使用 canvas 实现一个一笔一画写汉字的效果 All In One

copyright© xgqfrms 2022

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-06-16
 * @modified
 *
 * @description js 使用 canvas 实现一个一笔一画写汉字的效果 All In One
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @time O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/16384058.html
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

const canvas = document.querySelector('#app');
// log('canvas =', canvas);

const ctx = canvas.getContext('2d');
log('ctx =', ctx);
// CanvasRenderingContext2D

ctx.font = '32px serif';
// ctx.fillText('Hello world', 10, 50);


let finished = false;

function func () {
  log(`\nclear context ?`)
  // ctx.clearRect(0, 0, 600, 600);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  const texts = [...`abcdefghijklmn`].map(s => s.toUpperCase());
  // const texts = [...`abc`].map(s => s.toUpperCase());
  const timers = [];
  finished = false;
  for (let i = 0; i < texts.length; i++) {
    const timerId = setTimeout(() => {
      // fillText(text, x, y)
      // 覆盖清除 text ?
      // ctx.fillText('', 32 * (i + 1), 50);
      ctx.fillText(texts[i], 32 * (i + 1), 50);
      log('texts[i], 32 * (i + 1), 50 =', texts[i], 32 * (i + 1), 50);
    }, 1000 *  (i + 1));
    timers.push(timerId);
    if(i === texts.length - 1) {
      finished = true;
    }
  }
  if(finished) {
    setTimeout(() => {
      for (const timerId of timers) {
        clearTimeout(timerId);
      }
      // 性能优化,动画
      requestAnimationFrame(func);
    }, 1000 * (texts.length + 1));
  }
}

func();

live demo

Canvas API

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API

fillText(text, x, y)
fillText(text, x, y, maxWidth)

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText

strokeText(text, x, y)
strokeText(text, x, y, maxWidth)

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeText

clearRect(x, y, width, height)


https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect

Canvas Tutorial

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text

汉字笔画

核心思路:汉字分解成笔画图片, 按照坐标点,使用延迟依次拼接画出来即可!

汉字笔画生成器

https://www.an2.net/zi/

https://www.an2.net/zi/zi.php

SVG

Canvas 画板

refs

clearRect() Clear Canvas in JavaScript

https://www.delftstack.com/howto/javascript/clear-canvas-javascript/


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!