Reputation: 52
i have a problem with my code, i'm trying to draw a repeating pattern with a canvas but it keeps cutting off a piece. Does anyone know if it is possible to calculate what dimensions are needed for the canvas?
I use this code to generate the canvases:
const beginLength = 600;
const minLength = 1;
var alpha = 90;
var beta = -90;
const ratioA = 0.7;
const ratioB = 0.7;
const Point = function(x, y) {
this.X = x;
this.Y = y;
};
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
canvas.width = window.innerWidth * 1;
canvas.height = window.innerHeight * 1;
const drawLine = function(rootPoint, r, theta) {
context.beginPath();
const endX = rootPoint.X + r * Math.cos(theta);
const endY = rootPoint.Y + r * Math.sin(theta);
const endPoint = new Point(endX, endY);
context.moveTo(rootPoint.X, rootPoint.Y);
context.lineTo(endPoint.X, endPoint.Y);
context.strokeStyle = generateColor();
context.stroke();
if (r * ratioA < minLength || r * ratioB < minLength) {
return;
} else {
drawLine(endPoint, r * ratioA, theta + alpha);
drawLine(endPoint, r * ratioB, theta + beta);
}
};
function generateColor() {
return "rgb(" + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ", " + Math.floor(Math.random() * 256) + ")";
}
beta = beta / 180 * Math.PI;
alpha = alpha / 180 * Math.PI;
drawLine(new Point(canvas.width / 2, canvas.height), beginLength, Math.PI * 1.5);
<!DOCTYPE HTML>
<html>
<head>
<link rel="icon" type="image/x-icon" href="svg/draw.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Hubballi&family=Oxygen:wght@300&family=Roboto+Mono:wght@200&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/index.css" />
</head>
<body>
<canvas id="canvas" style="image-rendering: pixelated;"></canvas>
</body>
</html>
Upvotes: 1
Views: 121
Reputation: 36
I think your problem is that the positions of things that you are trying to draw are outside of the defines canvas, since it does seem to be cutting it off. Since you have defined the canvas dimensions to be equal to the windowwidth and windowheight, the canvas area will change based on how the window is resized, and if you zoom out, you may be able to see the whole canvas content. You could probably fix this by setting a varible that contained the max x value, and resize the canvas every time the value was updated, so that the content would always be shown. An easier solution would be to try setting the canvas width as a constant value that you can estimate and modify through trial and error. idk if i exactly understand your question, but i hope this helps. (this is my first stackoverflow answer :|)
Upvotes: 2