1 回答

TA貢獻1785條經驗 獲得超4個贊
問題是您在每個針跡之間繪制斜線。
讓事情變得更加戲劇化,這就是你正在做的事情。
function getRandomInt(min, max) {
? min = Math.ceil(min);
? max = Math.floor(max);
? return Math.floor(Math.random() * (max - min) + min);
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.beginPath();
ctx.strokeStyle = "#00000000";
ctx.moveTo(50, 0);
for (let i = 1; i < 200; i+= 10) {
? ctx.lineTo(50 + getRandomInt(-5, 10), i);
}
ctx.lineTo(500, 200);
ctx.lineTo(500, 0);
ctx.lineTo(50, 0);
ctx.stroke();
ctx.clip();
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);
<canvas id="canvas" width="300" height="300">
當渲染這些斜線時,瀏覽器將使用抗鋸齒來平滑線條,因為這通常是人們想要的。
但在您的情況下,您想要像素完美,因此解決方案是以階梯形狀圍繞像素邊界行走。這可以通過從最后一個 y 坐標到下一個 y 坐標繪制一條垂直線,然后繪制水平線來實現。
function getRandomInt(min, max) {
? min = Math.ceil(min);
? max = Math.floor(max);
? return Math.floor(Math.random() * (max - min) + min);
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// for high-res monitors
{
? const dPR = window.devicePixelRatio;
? canvas.width = canvas.height *= dPR
? ctx.scale( dPR, dPR );
}
ctx.beginPath();
ctx.strokeStyle = "#00000000";
ctx.moveTo(50, 0);
for (let i = 1; i < 200; i++) {
? let rand = getRandomInt( -1, 2 );
? ctx.lineTo( 50 + rand, i - 1 ); // from last y move horizontally
? ctx.lineTo( 50 + rand, i ); // move vertically
}
ctx.lineTo(500, 200);
ctx.lineTo(500, 0);
ctx.lineTo(50, 0);
ctx.clip();
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);
canvas { width: 300px; height: 300px }
<canvas id="canvas" width="300" height="300">
再次以更戲劇化的方式:
function getRandomInt(min, max) {
? min = Math.ceil(min);
? max = Math.floor(max);
? return Math.floor(Math.random() * (max - min) + min);
}
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.beginPath();
ctx.strokeStyle = "#00000000";
ctx.moveTo(50, 0);
for (let i = 1; i < 200; i+= 10) {
? const rand = getRandomInt(-5, 10);
? ctx.lineTo(50 + rand, i-10);
? ctx.lineTo(50 + rand, i);
}
ctx.lineTo(500, 200);
ctx.lineTo(500, 0);
ctx.lineTo(50, 0);
ctx.stroke();
ctx.clip();
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);
<canvas id="canvas" width="300" height="300">
添加回答
舉報