Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript draw using mouse Canvas with 3 axis

How is it / is it possible to draw using the mouse a canvas using 3 axis(x,y,z).

I know that one can draw a canvas on 2 axis and I have done that successfully.

But I have no idea of how I shall draw it on 3 axis (for example a cube).

Following shows some 2d canvas drawing functionallity

$(canvas).on('mousemove', function(e) {
mousex = parseInt(e.clientX-canvasx);
mousey = parseInt(e.clientY-canvasy);
if(mousedown) {
    ctx.beginPath();
    if(tooltype=='draw') {
        ctx.globalCompositeOperation = 'source-over';
        ctx.strokeStyle = 'black';
        ctx.lineWidth = 3;
    } else {
        ctx.globalCompositeOperation = 'destination-out';
        ctx.lineWidth = 10;
    }
    ctx.moveTo(last_mousex,last_mousey);
    ctx.lineTo(mousex,mousey);
    ctx.lineJoin = ctx.lineCap = 'round';
    ctx.stroke();
}
last_mousex = mousex;
last_mousey = mousey;
//Output
$('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);

});

The full code https://jsfiddle.net/ArtBIT/kneDX/.

But how can I add a z axis and draw a 3d canvas for instance a cube.

like image 566
utdev Avatar asked May 17 '17 12:05

utdev


1 Answers

With 2D it is simple, you have the X and Y coordinate of the mouse, and when a mouse button is clicked you can change pixels at that location in the canvas.

3D on the other hand is quite hard. Because of the extra dimension that does not exist on the 2D surface, you need to know how to control the 3D positions. And to make matters worse, with that third dimension comes all kinds of extra's that everyone likes to have: lightning and shadows, effects, focus, etc.

Simple drawing

In its most basic form, (set aside some arithmic) you can flatten the Z axis on the 2D surface with a single division. Suppose that you have a point in 3D which consists of three points on three axis (x3d, y3d, z3d) then you can do:

var x2d = x3d / z3d;
var y2d = y3d / z3d;

If you're new to 3D, you will want to play with this first. Here is a tutorial.

Advanced drawing

For just particles and lines this is rather straightforward, although you might want to use another perspective. But it gets more complicated soon when you use objects and want to rotate them in 3D space. This is why most people rely on an engine like three.js to do the 3D drawing for them.

Control 3D space

When drawing with the mouse, you need to map the 2D mouse movement to 3D for control. For examples, have a look a these 3D GUI's: Microsoft's Paint 3D, Google's Sketchup, and Blender. Note that the more kinds of mappings needs to be implemented (like scaling and other transformations) the more math is required.

like image 107
Code4R7 Avatar answered Sep 30 '22 06:09

Code4R7