How to save an image with css overlay color applied?

Example:-

https://codepen.io/coothead/full/gOrbPxz

Example Code:-

https://codepen.io/coothead/pen/gOrbPxz

Full Code:-

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>Canvas grayscale image</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: normal 1em / 1.5em  sans-serif;
 }

h1 {
	  font-size: 1em;
      text-align: center;
  }

h1 button {
    display: inline-block;
    width: 10em;
    margin: 0 0.5em;
    font-size: 1em;
    cursor: pointer;
 }

img {
    display: block;
    width: 100%;
    max-width: 48em;
    height: auto;
    margin: auto;
    cursor: pointer;
  }   
</style>

</head>
<body>

<h1>
 Use<button id="grayscale">show grayscale</button>to show or hide grayscale.<br>
 Right click to save image.
</h1>

<script>
(function( d ) {
   'use strict';

   var wdh, hgt, x = 0, y=  0, i, canvas, ctx, image, 
       imageData, data, gray, test = false, but,
       img = new Image();
       img.crossOrigin = 'Anonymous';  
       img.src = 'https://picsum.photos/id/308/768/512';
       img.onload = draw;

       canvas = d.createElement( 'canvas');
       canvas.setAttribute( 'width', 768 );
       canvas.setAttribute( 'height', 512 );

function  draw() {
    ctx = canvas.getContext( '2d' );

    wdh = canvas.width; 
    hgt = canvas.height;

    ctx.drawImage( img, 0, 0 );

    imageData = ctx.getImageData( x, y, img.width, img.height );
    data = imageData.data;

    for ( i = 0; i < data.length; i += 4) {
          var gray = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
          // red
          data[i] = gray;
          // green
          data[i + 1] = gray;
          // blue
          data[i + 2] = gray;
        }
    if ( test === true ){
        // overwrite original image
          ctx.putImageData( imageData, x, y );
        }

    image = d.createElement( 'img' );
    image.setAttribute( 'id',  'grayscale' );
    image.setAttribute( 'src', canvas.toDataURL() );
    image.setAttribute( 'width', 768 );
    image.setAttribute( 'height', 512 );
    image.setAttribute( 'alt', 'grayscale image' );

    d.body.insertBefore( image, d.querySelector( 'h1' ).nextSibling );
  }


   but = d.getElementById( 'grayscale' );
   but.addEventListener( 'click',
function(){
    d.body.removeChild(image);
    if ( test === true ){
         test = false; 
         but.textContent = 'show grayscale';
         draw();
      } 
    else {
         test = true;  
         but.textContent = 'hide grayscale';
         draw();
      }

}, false );

}(document));
</script>

</body>
</html>

coothead

1 Like