How would I do this using javascript?
I want to be able to download the image with the CSS color overlay applied to it.
I hope the makes it clearer.
https://jsfiddle.net/8cvom49d/
<div class="coloroverlay"></div>
.coloroverlay {
width: 1920px;
height: 1080px;
background-image: linear-gradient(to bottom,
rgba(255, 0, 187, 0.34),
rgba(255, 0, 187, 0.34)),
url(https://i.imgur.com/2jjLqzk.jpg);
}
You can’t, the only realistic way you could do it is non-trivial (relative to CSS) and involves JavaScript: it would be by writing the image to a <canvas>
and using some logic written in JS to adjust the colours on the rendered image (for completeness: you can also do other far more complex things like run an image processing program in a worker, or manually adjusting the image code, but these things are not likely to be practical).
CSS is just a visual layer in browsers, it doesn’t alter images.
How would I set it up using <canvas>
?
How would I apply this code to the javascript section?
background-image: linear-gradient(to bottom,
rgba(255, 0, 187, 0.34),
rgba(255, 0, 187, 0.34)),
url(https://i.imgur.com/2jjLqzk.jpg);
https://jsfiddle.net/s89qvcau/
var img = new Image();
img.crossOrigin = "";
img.onload = draw; img.src = "https://i.imgur.com/2jjLqzk.jpg";
function draw() {
var canvas = document.querySelector("canvas"),
ctx = canvas.getContext("2d");
canvas.width = this.width;
canvas.height = this.height;
// filter
if (typeof ctx.filter !== "undefined") {
ctx.filter = "sepia(0.8)";
ctx.drawImage(this, 0, 0);
}
else {
ctx.drawImage(this, 0, 0);
// TODO: manually apply filter here.
}
document.querySelector("img").src = canvas.toDataURL();
}
Been a while since I’ve used canvas, but afaics just a linear gradient (this is first result) https://www.w3schools.com/tags/canvas_createlineargradient.asp
1 Like
Thanks!
https://jsfiddle.net/rx9L3ozq/
h1 {
text-align: center;
}
img {
display: block;
width: 60%;
height: auto;
margin: auto;
cursor: pointer;
}
<h1>
Image with overlay<br>
Right click to save.
</h1>
(function( d ) {
'use strict';
var wdh, hgt, canvas, ctx, grd, image,
img = new Image();
img.crossOrigin = '';
img.src = 'https://i.imgur.com/2jjLqzk.jpg';
img.onload = draw;
canvas = d.createElement( 'canvas');
canvas.setAttribute( 'width', 1920 );
canvas.setAttribute( 'height', 1080 );
function draw() {
ctx = canvas.getContext( '2d' );
wdh = canvas.width;
hgt = canvas.height;
ctx.drawImage( this, 0, 0 );
grd = ctx.createLinearGradient( wdh/2, 0, wdh/2, hgt );
grd.addColorStop( 0, 'rgba(255, 0, 187, 0.34)');
grd.addColorStop( 1, 'rgba(255, 0, 187, 0.34)' );
ctx.fillStyle = grd;
ctx.rect(0, 0, wdh, hgt);
ctx.fill();
image = d.createElement( 'img' );
image.setAttribute( 'id', 'overlaid-image' );
image.setAttribute( 'src', canvas.toDataURL() );
image.setAttribute( 'width', 1920 );
image.setAttribute( 'height', 1080 );
image.setAttribute( 'alt', 'overlaid image' );
d.body.insertBefore( image, d.querySelector( 'h1' ).nextSibling );
}
}( document ));
1 Like