gpt4 book ai didi

javascript - Canvas 上的对 Angular 线以不同的颜色/不透明度绘制

转载 作者:行者123 更新时间:2023-11-29 20:31:16 24 4
gpt4 key购买 nike

我在特定尺寸的 HTML Canvas 上绘制对 Angular 线,但其中一些似乎具有与其他不同的颜色/不透明度。我希望它们具有相同的颜色/不透明度。

Diagonal lines picture

我用来生成此输出的代码如下:

let artist = {
step: 50,
distanceBetweenLines: 10,
verticalDifferenceInLines: 150,
}

window.onload = function () {
canv = document.getElementById("gc");
ctx = canv.getContext("2d");
ctx.translate(0.5, 0.5);
ctx.lineWidth = "1";
ctx.strokeStyle = "black";

draw();
}

function draw () {
let step = artist.step;
let d = artist.distanceBetweenLines;
let v = artist.verticalDifferenceInLines;

for (let x = 0; x < 500; x += step) {
for (let y = 0; y < 500; y += step) {
let increment = 30;
line({x:x, y: y}, {x:x+increment, y: y+increment});
}
}
}

function line(init, end) {
ctx.beginPath();
ctx.moveTo(init.x, init.y);
ctx.lineTo(end.x, end.y);
ctx.stroke();
}

为什么我在某些行上得到这种效果?

最佳答案

这是一个 chrome 错误。我开了一个issue here .

这基本上是硬件加速的问题,如果您禁用它,即使在 Chrome 中也能很好地呈现。

要解决此问题,您可以编写一个更大的路径,其中将包含您的所有行并仅调用一次 stroke():

let artist = {
step: 50,
distanceBetweenLines: 10,
verticalDifferenceInLines: 150,
}

window.onload = function() {
canv = document.getElementById("gc");
ctx = canv.getContext("2d");
ctx.translate(0.5, 0.5);
ctx.lineWidth = "1";
ctx.strokeStyle = "black";

draw();
}

function draw() {
let step = artist.step;
let d = artist.distanceBetweenLines;
let v = artist.verticalDifferenceInLines;

// a single big path
ctx.beginPath();
for (let x = 0; x < 500; x += step) {
for (let y = 0; y < 500; y += step) {
let increment = 30;
line({
x: x,
y: y
}, {
x: x + increment,
y: y + increment
});
}
}
// stroke only once
ctx.stroke();
}

function line(init, end) {
ctx.moveTo(init.x, init.y);
ctx.lineTo(end.x, end.y);
}
<canvas id="gc" width="500" height="500"></canvas>

但是对于这个精确的绘图,使用 CanvasPattern 会更好:

// An helper function to create CanvasPatterns
// returns a 2DContext on which a simple `finalize` method is attached
// method which does return a CanvasPattern from the underlying canvas
function patternMaker( width, height ) {
const canvas = document.createElement( 'canvas' );
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext( '2d' );
ctx.finalize = (repetition = "repeat") => ctx.createPattern( canvas, repetition );
return ctx;
}

const canvas = document.getElementById("gc");
const ctx = canvas.getContext("2d");

const step = 50;
const offset = 30;

const patt_maker = patternMaker( step, step );
patt_maker.translate( 0.5, 0.5 );
patt_maker.moveTo( 0, 0 );
patt_maker.lineTo( offset, offset );
patt_maker.stroke();
const patt = patt_maker.finalize();

ctx.fillStyle = patt;
ctx.fillRect( 0, 0, canvas.width, canvas.height );
<canvas id="gc" width="500" height="500"></canvas>

关于javascript - Canvas 上的对 Angular 线以不同的颜色/不透明度绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053363/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com