모노톤 이미지에 색칠하기

투과 부분이 있는 모노톤의 화상을 준비.



준비한 화상을 캔버스로 합성하여 이하와 같이 한다.



데모: htps : //도 49. 기주 b. 이오/쿠이타/20170223/

MonotoneCanvas.js
class MonotoneCanvas {
  constructor(opts={}) {
    this.canvas = opts.canvas || document.createElement('div');
    this.fileSrc = opts.fileSrc || '';
    this.width = isNaN(opts.width) ? 0 : opts.width;
    this.height = isNaN(opts.height) ? 0 : opts.height;
    this.color = opts.color || '#000';

    this.init();
  }

  init() {
    this.preloadCanvas().then((value) => {
      // canvasのプリロード後に描画
      this.draw(value);
    })
  }

  preloadCanvas() {
    return new Promise((resolve, reject) => {
      const canvas = document.createElement("canvas");
      let img = new Image();
      img.src = this.fileSrc;
      img.addEventListener('load', () => {
        // 1度canvasに描く
        const ctx = canvas.getContext("2d");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
        resolve(canvas);
      }, false)
    })
  }

  draw(preloadCanvas) {
    const canvas = this.canvas;
    const ctx = canvas.getContext('2d');
    canvas.width = this.width;
    canvas.height = this.height;

    ctx.fillStyle = this.color;
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.globalCompositeOperation = 'destination-in';

    // 一度描画したcanvasを再びcanvasに描画する
    ctx.drawImage(preloadCanvas, 0, 0, canvas.width, canvas.height);
  }

}

사용
(() => {

  new MonotoneCanvas({
    canvas: document.getElementById('canvas'),
    fileSrc: 'wave.png',
    width: 640,
    height: 87,
    color: '#f00'
  })
  new MonotoneCanvas({
    canvas: document.getElementById('canvas2'),
    fileSrc: 'wave.png',
    width: 640,
    height: 87,
    color: '#0f0'
  })
  new MonotoneCanvas({
    canvas: document.getElementById('canvas3'),
    fileSrc: 'wave_black.png',
    width: 640,
    height: 87,
    color: '#00f'
  })

})()

좋은 웹페이지 즐겨찾기