CSS代码:
.clarendon-filter {
filter: contrast(1.2) saturate(1.35);
display: inline-block;
position: relative;
}
.clarendon-filter::before {
content: '';
display: block;
height: 100%;
width: 100%;
top: 0; left: 0;
position: absolute;
background: rgba(127,187,227,.2);
mix-blend-mode: overlay;
pointer-events: none;
}
HTML代码:
<h4>原始效果</h4>
<p><img src="./example.jpg" width="256" height="192"></p>
<h4>CSS图像处理效果(右键另存是原图)</h4>
<div id="input" class="clarendon-filter">
<img src="./example.jpg" width="256" height="192">
</div>
<h4>后台存储的处理后的图像(右键另存是合成图)</h4>
<p><img id="output" width="256" height="192"></p>
JS代码:
// 输入
var eleInput = document.getElementById('input');
// 输出
var eleOutput = document.getElementById('output');
/**
* CSS渲染的图像效果转换成纯图像
* @param {[type]} dom [description]
* @return {[type]} 返回的是图像的base64信息
*/
var cssRenderImage2PureImage = function (dom, callback) {
if (!dom) {
return this;
}
var pixelRatio = window.devicePixelRatio || 1;
// 尺寸
var width = dom.offsetWidth * pixelRatio;
var height = dom.offsetHeight * pixelRatio;
// 复制DOM节点
var cloneDom = dom.cloneNode(true);
cloneDom.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
// 图像元素处理
var eleImg = cloneDom.querySelector('img');
eleImg.width = width;
eleImg.height = height;
// 图像变成base64
var tempImg = new Image();
tempImg.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
// 上下文
var context = canvas.getContext('2d');
// 绘制在画布上
context.drawImage(tempImg, 0, 0, width, height);
// 图像转换
eleImg.src = canvas.toDataURL();
// 进一步转换
var svgImg = new Image();
svgImg.onload = function () {
// canvas绘制合成图
context.clearRect(0, 0, width, height);
context.drawImage(svgImg, 0, 0, width, height);
// 使用jpeg格式
callback && callback(canvas.toDataURL('image/jpeg'));
};
svgImg.src = 'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '"><foreignObject x="0" y="0" width="100%" height="100%">'+
new XMLSerializer().serializeToString(cloneDom).replace(/#/g, '%23').replace(/\n/g, '%0A') +
document.querySelector('style').outerHTML +
'</foreignObject></svg>';
};
tempImg.src = eleImg.src;
};
// 执行
cssRenderImage2PureImage(eleInput, function (url) {
eleOutput.src = url;
});