将CSS类应用于Canvas [英] Applying CSS Class to Canvas

查看:97
本文介绍了将CSS类应用于Canvas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多CSS过滤器类,可以使用CSS过滤器将它们应用于图像.我的目标是使用应用于dataURL的过滤器转换图像.

I have a lot of css filter classes that can be applied to an image using the the CSS filter. My goal is to convert the image with the filter applied to dataURL.

为此,我将图像放置在画布中,然后在应用滤镜后保存图像.这是一个例子

To do so, I'm placing the image into a canvas then saving the image after I applied the filter. Here's an example

  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类应用于画布对象.最糟糕的情况是我将所有过滤器都转换为字符串对象数组,但我很好奇.谢谢!

While this works fine applying a single filter, I have more than 30 filters made in my css class, and I would like to know if there's a way to apply a css class to a canvas object. Worst case scenario is for me to convert all of my filters into an array of string objects, but I'm just very curious. Thanks!

对画布上下文的引用链接: https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D

Link for reference to canvas context: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

推荐答案

您可以简单地读取 getComputedStyle(canvasElement).filter 返回的值,并将其用作上下文的 filter .

You can simply read the value returned by getComputedStyle(canvasElement).filter and use it as your context's 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类应用于Canvas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆