Skip to content Skip to sidebar Skip to footer

Applying Css Class To Canvas

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 placi

Solution 1:

You can simply read the value returned by getComputedStyle(canvasElement).filter and use it as your context's filter.

var img=newImage();img.crossOrigin=1;img.onload=draw;
img.src="https://upload.wikimedia.org/wikipedia/commons/5/55/John_William_Waterhouse_A_Mermaid.jpg";


functiondraw() {
 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);
}
functionsaveAsIMG(blob) {
  var img = newImage();
  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;
}
<canvasid="canvas"></canvas>

Post a Comment for "Applying Css Class To Canvas"