我有很多可以使用 CSS 过滤器应用于图像的 css 过滤器类。我的目标是使用应用于 dataURL 的过滤器来转换图像。
为此,我将图像放入 Canvas ,然后在应用滤镜后保存图像。这是一个例子
const img = this.img // my <img />
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
context.filter = 'grayscale(2)'
context.drawImage(img, 0, 0)
const finalImg = canvas.toDataURL()
虽然应用单个过滤器效果很好,但我在我的 css 类中制作了 30 多个过滤器,我想知道是否有办法将 css 类应用于 Canvas 对象。最坏的情况是我将所有过滤器转换为字符串对象数组,但我很好奇。谢谢!
Canvas 上下文引用链接:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D
最佳答案
您可以简单地读取 getComputedStyle(canvasElement).filter
返回的值并将其用作上下文的 filter
。
var img=new Image();img.crossOrigin=1;img.onload=draw;
img.src="https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg";
function draw() {
canvas.width = this.width/4; canvas.height = this.height/4;
var ctx = canvas.getContext('2d');
ctx.font = '15px sans-serif';
ctx.fillStyle = 'white';
for(var i=1; i<5; i++) {
// set the class
canvas.className = 'filter' + i;
// retrieve the filter value
ctx.filter = getComputedStyle(canvas).getPropertyValue('filter');
ctx.drawImage(img, 0,0, img.width/4, img.height/4);
ctx.filter = 'none';
ctx.fillText('filter' + i, 20, 20);
// export
canvas.toBlob(saveAsIMG);
}
ctx.drawImage(img, 0,0, img.width/4, img.height/4);
ctx.fillText('canvas - no filter', 20, 20);
}
function saveAsIMG(blob) {
var img = new Image();
img.onload = function(){URL.revokeObjectURL(img.src);};
img.src = URL.createObjectURL(blob);
document.body.appendChild(img);
}
.filter1 {
filter: blur(5px);
}
.filter2 {
filter: grayscale(60%) brightness(120%);
}
.filter3 {
filter: invert(70%);
}
.filter4 {
filter: none;
}
<canvas id="canvas"></canvas>
关于css - 将 CSS 类应用于 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291239/