LoginSignup
2
1

More than 5 years have passed since last update.

モノトーン画像に色をつける

Posted at

透過部分のあるモノトーンの画像を用意。

wave_black.png

用意した画像をcanvasで合成して以下のようにする。

スクリーンショット 2017-02-23 18.22.03.png

デモ:https://mo49.github.io/qiita/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'
  })

})()
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1