It looks like you’re example is working fine. I think you might be misunderstanding how the applyMatrix() function works. In effect, you’re calling translate(width/2, height/2).
Once it’s called, any drawing functions, like ellipse(), or in your case, line(), has the matrix applied to it.
// translating origin to the sketch center
applyMatrix(1,0,0,1,width/2,height/2)
stroke(0)
// This should actually draw a line from center to mouse, but it doesn't
// as showed by the black line
line(0,0,mouseX,mouseY)
line() only knows this: take 4 numbers, apply the matrix to them, draw the line. mouseX and mouseY are any other numbers.
After I applied the matrix. what I really needed to draw is -
line(0,0,mouseX-width/2,mouseY-height/2)
This is something that I should automatically get. I should not be again trying to figure out how I can draw the line by comparing the changes that I made by applying the matrix.
Have you considered to write a small function which translates the canvas and the mouse coordinates? That way you only have to mention the translate values once:
let mX, mY;
function setup() {
// code
}
function draw() {
translateMore(width/2, height/2);
// code
}
function translateMore(_x, _y) {
mX = mouseX - _x;
mY = mouseY - _y;
translate(_x, _y);
}
Note that in WEBGL there isn’t actually a unique solution for this problem. That is because applyMatrix is 3D, and the mouse is 2D. So the question “after rotation, where can I draw a line such that it intersects ends visually intersecting with the mouse?” has a set of answers that form a ray cast from the mouse into 2D space. You would need to further constrain those answers based on something – the plane z=0, or perpendicular to point A with respect to the camera, etc. You can however ask the question the other way – for a given 3D point, what is the 2D screen position (screenX): see the library https://github.com/bohnacker/p5js-screenPosition
There is a unique solution in 2D – it is just that this is a special case for matrices.
You may also be interested in this past issue, and the links in it: