透過部分のあるモノトーンの画像を用意。
用意した画像をcanvasで合成して以下のようにする。
デモ: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'
})
})()