I want to create an animated canvas, which is also using a path. I wrote this code by combining two scripts: script1 and script2.
The script throws an exception: Failed to execute 'fill' on 'CanvasRenderingContext2D': The provided value '256' is not a valid enum value of type CanvasFillRule.
What can be wrong?
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const r = new Path2D();
r.moveTo(0, 0);
r.lineTo(800, 0);
r.lineTo(800, 200);
r.lineTo(0, 400);
r.lineTo(0, 0);
r.closePath();
let time = 0;
const color = function (x, y, r, g, b) {
context.fillStyle = `rgb(${r}, ${g}, ${b})`
context.fill(r);
}
const R = function (x, y, time) {
return (Math.floor(191 + 64 * Math.cos((x * x - y * y) / 300 + time)));
}
const G = function (x, y, time) {
return (Math.floor(191 + 64 * Math.sin((x * x * Math.cos(time / 4) + y * y * Math.sin(time / 3)) / 300)));
}
const B = function (x, y, time) {
return (Math.floor(191 + 64 * Math.sin(5 * Math.sin(time / 9) + ((x - 100) * (x - 100) + (y - 100) * (y - 100)) / 1100)));
}
const startAnimation = function () {
for (x = 0; x <= 30; x++) {
for (y = 0; y <= 30; y++) {
color(x, y, R(x, y, time), G(x, y, time), B(x, y, time));
}
}
time = time + 0.03;
window.requestAnimationFrame(startAnimation);
}
startAnimation();
body {
height: 400px;
width: 500px;
}
canvas {
width: 100%;
height: 100%;
}
<canvas id="canvas" width="32px" height="32px">
The issue is that you are exceeding the bounds of a color value required in the rgb() function.
Valid numbers are 0-255
You will need to modify R(), G(), and B()
After the result is calculated in any of those functions, subtract 1 from it before returning.
EDIT:* The bounds of color values needed to be fixed, but it wasn’t the main issue.
The problem is that you create a path and name the variable r
Inside the color function, you take r as a parameter.
When you call fill, the value for Red is being passed, not the path itself.
Change your path variable to something other than r and you’ll be golden.