如何保存应用了 CSS 叠加颜色的图像?
Posted
技术标签:
【中文标题】如何保存应用了 CSS 叠加颜色的图像?【英文标题】:How to save an image with CSS overlay color applied? 【发布时间】:2020-07-26 17:31:46 【问题描述】:我将如何使用 javascript 来做到这一点?
我希望能够下载应用了 CSS 颜色叠加的图像。
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);
【问题讨论】:
【参考方案1】:(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 ));
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>
【讨论】:
以上是关于如何保存应用了 CSS 叠加颜色的图像?的主要内容,如果未能解决你的问题,请参考以下文章