canvas - 画布绘制对角 CSS 渐变
问题描述
我想在画布中重现对角 CSS 线性渐变,但结果有点不同。我的目标是我的画布显示的内容与 CSS 显示的内容完全相同。
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var angle = 45 * Math.PI / 180,
x2 = 200 * Math.cos(angle),
y2 = 200 * Math.sin(angle);
var gradient = ctx.createLinearGradient(0, 0, x2, y2);
gradient.addColorStop(0, 'RGBA(0, 255, 0, 1)');
gradient.addColorStop(1, 'RGBA(255, 0, 0, 1)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
div {
background: linear-gradient(135deg, RGBA(0, 255, 0, 1) 0%, RGBA(255, 0, 0, 1) 100%);
width: 200px;
height: 100px;
}
<canvas id="canvas"></canvas>
<div>
</div>
我应该如何改进画布渲染以获得与 CSS 相同的结果?
解决方案
计算背后的想法:https ://drafts.csswg.org/css-images-3/#example-b6f5099c
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
const width = 200;
const height = 100;
const angleInDeg = 135;
// Compute angle in radians - CSS starts from 180 degrees and goes clockwise
// Math functions start from 0 and go anti-clockwise so we use 180 - angleInDeg to convert between the two
const angle = ((180 - angleInDeg) / 180) * Math.PI
// This computes the length such that the start/stop points will be at the corners
const length = Math.abs(width * Math.sin(angle)) + Math.abs(height * Math.cos(angle))
// Compute the actual x,y points based on the angle, length of the gradient line and the center of the div
const halfx = Math.sin(angle) * length / 2.0
const halfy = Math.cos(angle) * length / 2.0
const cx = width / 2.0
const cy = height / 2.0
const x1 = cx - halfx ;
const y1 = cy - halfy;
const x2 = cx + halfx;
const y2 = cy + halfy;
var gradient = ctx.createLinearGradient(x1, y1, x2, y2);
gradient.addColorStop(0, 'RGBA(0, 255, 0, 1)');
gradient.addColorStop(1, 'RGBA(255, 0, 0, 1)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 200, 100);
div {
background: linear-gradient(135deg, RGBA(0, 255, 0, 1) 0%, RGBA(255, 0, 0, 1) 100%);
width: 200px;
height: 100px;
}
<canvas id="canvas"></canvas>
<div>
</div>
推荐阅读
- reactjs - 为什么当我在渲染中做出反应时,Leaflet 会向我抛出这个错误?
- python - discord.Embed 不被视为嵌入 discord.py
- kotlin - kotlin 上的 Gradle 任务。声明 OutputFile 值
- vue.js - 图像加载离子
- javascript - 如何在 Javascript 中使用模板文字进行连接?
- powershell - 如何安排 Powershell JOB 每 5 分钟运行一次
- javascript - 等效于 C# SHA512 的 Javascript
- c - 在 MacOS Catalina 上使用 openmp 库
- azure - Windows 2019 IIS On Premise Application Insight Monitor 状态
- typescript - 基于值的参数类型