【发布时间】:2019-02-20 19:59:14
【问题描述】:
我有一个使用 HTML Canvas 创建线性渐变的网络工具。我想将这些渐变转换为有效的 CSS 渐变。我尝试了我所知道的所有数学知识(不是很多)......没有真正的结果。
我现在知道的事情: - CSS 线性渐变可以从负值开始,而 Canvas 渐变不能。
这是我目前的工作:
var width = 50;
var height = 50;
var handlesPositions = [
{
"x": 0.16,
"y": -1.98
},
{
"x": 0.84,
"y": 2.98
},
]
var colorStops = [
{
"color": "#FF0000",
"position": 0.359
},
{
"color": "#0094FF",
"position": 0.495
},
{
"color": "#FFFF00",
"position": 0.652
}
];
// CANVAS
var c = document.getElementById("source");
var ctx = c.getContext("2d");
var x0 = handlesPositions[0].x * width;
var y0 = handlesPositions[0].y * height;
var x1 = handlesPositions[1].x * width;
var y1 = handlesPositions[1].y * height;
var grd = ctx.createLinearGradient(x0, y0, x1, y1);
grd.addColorStop(colorStops[0].position, colorStops[0].color);
grd.addColorStop(colorStops[1].position, colorStops[1].color);
grd.addColorStop(colorStops[2].position, colorStops[2].color);
ctx.fillStyle = grd;
ctx.fillRect(0, 0, 50, 50);
// CANVAS TO CSS
function canvasToLinearGradient(handles, stops) {
const handle0 = handles[0];
const handle1 = handles[1];
const ydiff = handle1.y - handle0.y;
const xdiff = handle0.x - handle1.x;
const angle = Math.atan2(-xdiff, -ydiff);
const cssStops = stops.map((stop) => {
return `${stop.color} ${Math.round(stop.position * 100)}%`;
}).join(', ');
return `linear-gradient(${angle}rad, ${cssStops})`;
}
document.getElementById("current").style.backgroundImage = canvasToLinearGradient(handlesPositions, colorStops);
#goal {
background: linear-gradient(172.19deg, #FF0000 -12.39%, #0094FF 48.06%, #FFFF00 117.89%);
}
.row {
display: flex;flex-direction:row;justify-content:space-between;align-items:center;margin-bottom:10px
}
<div style="width: 230px">
<div class="row">Goal <div id="goal" style="width:50px;height:50px;"></div></div>
<div class="row">Source <canvas id="source" width="50" height="50"></canvas></div>
<div class="row">Current result <div id="current" style="width:50px;height:50px;"></div>
</div>
【问题讨论】:
-
这可能对你有帮助:stackoverflow.com/a/51884567/8620333 .. 你会在那里找到一些数学。检查您不必使用背景大小的第二部分
-
@TemaniAfif 无法正常工作。 :(
-
好的很快就会添加答案
标签: javascript html css html5-canvas linear-gradients