首页 > 解决方案 > 画布绘制对角 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 相同的结果?

标签: canvas

解决方案


在这里找到解决方案:https ://www.reddit.com/r/gamedev/comments/n2xs41/calculate_degrees_of_linear_gradient_in_canvas/gwnjh3a/

计算背后的想法:https ://drafts.c​​sswg.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>


推荐阅读