<script src="https://assets.codepen.io/3560077/CanvasAnimater.js"></script>
<canvas id="myCanvas"></canvas>
<script src="./script.js"></script>
// create a CanvasAnimater object that targets a canvas element with id='myCanvas'
let canvasAnimater = new CanvasAnimater('myCanvas');
// get the '2D' rendering canvas context
let ctx = canvasAnimater.context;
// set the canvas width and height dimensions to 300x300
// NOTE: this setting is bypassed if canvas is flexed
canvasAnimater.size(300,300)
// flex the canvas to fill the entire window
canvasAnimater.flex(true);
// define and set a draw function that draws a black background, gray box, and a white disk
canvasAnimater.draw = function (t) {
// get interaction variables for normalized mouse position
let x_pos = canvasAnimater.mouseX1;
let y_pos = canvasAnimater.mouseY1;
let W = canvasAnimater.width;
let H = canvasAnimater.height;
// draw a black background
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, W, H);
// declare a side length of the box
let B = 0.75*Math.min(W,H);
// draw a gray box centered in the canvas
ctx.fillStyle = 'gray';
ctx.fillRect(W/2 - B/2 , H/2 - B/2, B, B);
// draw a white disk at mouse position bounded to the box
ctx.beginPath();
ctx.arc(W/2 + B/2*x_pos, H/2 + B/2*y_pos , 10, 0, 2*Math.PI);
ctx.closePath();
ctx.fillStyle = 'white';
ctx.fill();
// draw reference text displaying interaction variables
displayInteractionText();
}
// draws reference text displaying interaction variables
function displayInteractionText() {
ctx.font = '14px Monospace';
ctx.fillText(`mouseX : ${canvasAnimater.mouseX}`, 20, 20);
ctx.fillText(`mouseY : ${canvasAnimater.mouseY}`, 160, 20);
ctx.fillText(`mouseX1 : ${canvasAnimater.mouseX1.toFixed(2)}`, 20, 40);
ctx.fillText(`mouseY1 : ${canvasAnimater.mouseY1.toFixed(2)}`, 160, 40);
}
// enable interaction for 'mousedownmove'
canvasAnimater.interact('mousedownmove', true);
// set the interaction origin to the center of the canvas
canvasAnimater.interactionOrigin(0.5,0.5);
// set a time evolution range
canvasAnimater.evolve(0);
// loop the animation over the evolution time range
canvasAnimater.loop(false);
// set the render rate in frames-per-second
canvasAnimater.FPS(50);
// set animation mode to 'rate' with 'animation_rate' = 0.03
canvasAnimater.mode('rate', 0.03);
// render the animation
canvasAnimater.animate();
This Pen doesn't use any external CSS resources.