Affichage des articles dont le libellé est Draw. Afficher tous les articles
Affichage des articles dont le libellé est Draw. Afficher tous les articles

JavaScript Drawing Application Source Code

How To Create a Drawing Application in JavaScript, HTML and CSS

How To Create a Drawing Application in JavaScript, HTML and CSS


In this JavaScript Tutorial, we will see how to create a Drawing application using  JavaScript, HTML5, CSS3.
In this project tutorial we will build a painting project with multiple drawing tools, shapes, colors, and even undo/redo functionality. 

What We Are Gonna Use In This Project:

- JavaScript Programming Language.
- HTML and CSS.
- Font-awesome.
- Visual Studio Editor.






Project Source Code:



     - Canvas History Recorder

Captures the current canvas state as a data URL and stores it in the undo stack for later restoration.


// Save the current drawing to history so we can undo later
function saveState() {
// Convert canvas to a data URL (like a photo of the drawing)
undoStack.push(canvas.toDataURL());
// Clear redo history when new drawing happens
// (can't redo after drawing something new)
redoStack = [];
}



     - Canvas State Restorer
    
Takes a saved canvas state and redraws it on the canvas, clearing any existing content first.

// Put a saved drawing back on the canvas (for undo/redo)
function restoreState(state) {
// Create a new image from the saved data
const img = new Image();
img.src = state;
// When image loads, draw it on the canvas
img.onload = () => {
// Clear canvas first
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the saved state
ctx.drawImage(img, 0, 0);
};
}




     - Drawing Session Initiator

Activates drawing mode when mouse is pressed down and captures the starting coordinates for the drawing operation.


// Start drawing when mouse button is pressed down
function startDrawing(e) {
isDrawing = true;
// Get mouse position and remember it
[lastX, lastY] = [e.offsetX, e.offsetY];

// For shapes, take a snapshot of current canvas
// This helps us show a preview while dragging
if (currentShape !== 'freehand') {
snapshot = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
}



     - Main Drawing Function

Handles all drawing operations based on current tool and shape settings, managing different drawing modes like freehand, lines, rectangles, and circles.


// Do the actual drawing as mouse moves
function draw(e) {
// Don't do anything if we're not in drawing mode
if (!isDrawing) return;

// Get current mouse position
const x = e.offsetX;
const y = e.offsetY;

// Set color based on current tool
// If using eraser, use background color (to "erase")
// Otherwise use the selected drawing color
ctx.strokeStyle = currentTool === 'eraser' ? bgColor : currentColor;
ctx.fillStyle = currentTool === 'eraser' ? bgColor : currentColor;

// Set line thickness and style based on selected tool
if (currentTool === 'brush') {
// Brush is thicker than pencil
ctx.lineWidth = brushSize.value * 2;
ctx.lineCap = 'round'; // Round end caps for smooth lines
ctx.lineJoin = 'round'; // Round corners for smooth lines
} else if (currentTool === 'pencil' || currentTool === 'eraser') {
ctx.lineWidth = brushSize.value;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
}

// Do different drawing based on selected shape
switch (currentShape) {
case 'freehand':
// Free drawing - follow the mouse movement exactly
ctx.beginPath(); // Start a new line
ctx.moveTo(lastX, lastY); // Move to where we started
ctx.lineTo(x, y); // Draw to current position
ctx.stroke(); // Actually draw the line
[lastX, lastY] = [x, y]; // Update position for next move
break;

case 'line':
// Straight line - from start point to current mouse position
ctx.putImageData(snapshot, 0, 0); // Restore canvas to before drag
ctx.beginPath(); // Start a new line
ctx.moveTo(lastX, lastY); // Move to start position
ctx.lineTo(x, y); // Draw to current position
ctx.stroke(); // Actually draw the line
break;

case 'rectangle':
// Rectangle - from start point with width/height to mouse
ctx.putImageData(snapshot, 0, 0); // Restore canvas to before drag
const width = x - lastX; // Calculate width based on mouse
const height = y - lastY; // Calculate height based on mouse

// Fill the rectangle if fill option is on
if (fillShape) {
ctx.fillRect(lastX, lastY, width, height);
}

// Always draw the outline
ctx.strokeRect(lastX, lastY, width, height);
break;

case 'circle':
// Circle - center at start point, size to mouse position
ctx.putImageData(snapshot, 0, 0); // Restore canvas to before drag

// Calculate radius (distance from center to mouse)
const radius = Math.sqrt(Math.pow(x - lastX, 2) + Math.pow(y - lastY, 2));

ctx.beginPath(); // Start a new shape
ctx.arc(lastX, lastY, radius, 0, 2 * Math.PI); // Draw full circle

// Fill the circle if fill option is on
if (fillShape) { ctx.fill(); }

// Always draw the outline
ctx.stroke();
break;

}

}




     - Drawing Session Finalizer

Deactivates drawing mode when mouse is released and saves the current state to the undo history.


// Stop drawing when mouse button is released
function stopDrawing() {
if (isDrawing) {
isDrawing = false;
// Save to history when finished drawing
// (so we can undo if needed)
saveState();
}
}



     - Previous State Restorer

Moves backward through the drawing history by one step, allowing users to reverse their last action.


// Go back one step in drawing history
function undo() {
// Need at least 2 items in stack (original blank + at least one drawing)
if (undoStack.length > 1) {
// Move current drawing to redo stack
redoStack.push(undoStack.pop());
// Show the previous drawing
restoreState(undoStack[undoStack.length - 1]);
}
}




     - Forward State Restorer

Moves forward through the drawing history by one step, allowing users to restore previously undone actions.


// Go forward one step in drawing history
function redo() {
if (redoStack.length > 0) {
// Get the most recent redo state
const stateToRedo = redoStack.pop();
// Add it back to the undo history
undoStack.push(stateToRedo);
// Show this drawing
restoreState(stateToRedo);
}
}



     - Background Color Updater

Updates the canvas background color using the selected color from the color picker and refreshes the display.


// Change the canvas background color
function changeBackgroundColor() {
// Get color from the color picker
const newColor = customColorPicker.value;
bgColor = newColor;
// Apply by clearing canvas with new background color
clearCanvas();
}



     - Canvas Content Eraser

Completely clears the canvas and fills it with the current background color, then saves this blank state.


// Clear everything from the canvas
function clearCanvas() {
// Fill entire canvas with background color
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Save this blank state to history
saveState();
}



     - Active Tool Selector

Updates the current tool setting and provides visual feedback by highlighting the selected tool button.


// Highlight the active tool button
function setActiveTool(toolName) {
currentTool = toolName;
// Remove highlight from all buttons first
document.querySelectorAll('.toolbar button').
forEach(btn => btn.classList.remove('active'));
// Add highlight to selected tool button
document.getElementById(`${toolName}Btn`).classList.add('active');
}



     - Drawing Export Handler

Converts the current canvas content to a PNG image and triggers a download for the user.


// Save drawing as a PNG image file
function saveCanvas() {
// Create a download link
const link = document.createElement('a');
link.download = 'drawing.png'; // File name
// Get the canvas data as an image URL
link.href = canvas.toDataURL();
// Trigger the download
link.click();
}







Java - How to create a cube in java swing

How to Create a Cube in Java NetBeans

How to Create a Cube in Java NetBeans


In this Java Tutorial we will see How To draw a cube with orange outline on a black background using a JPanel, Graphics and Graphics2D objects in Java Swing using NetBeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.


What We Will Do In This Project:
- Create a drawLine method to draw lines on the panel representing the edges of the cube.
- Create a drawRectangularFace method to draw a rectangular face of the cube by connecting lines.
- Create a connectFaces method to connects the front and back faces of the cube by drawing additional lines.






Project Source Code:


package new_tutorials;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class ThreeDCube extends JPanel{

    private static final int FRAME_WIDTH = 800;
    private static final int FRAME_HEIGHT = 600;
    private static final int CUBE_SIZE = 200;
    
    public ThreeDCube(){
        setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
    }
    
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        // Set the stroke to a thicker line
        g2d.setStroke(new BasicStroke(5));
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
        // Calculate the position to center the cube
        int x = (FRAME_WIDTH - CUBE_SIZE) / 2;
        int y = (FRAME_HEIGHT - CUBE_SIZE) / 2;
        // Draw front face
        drawRectangularFace(g2d, x, y, CUBE_SIZE, CUBE_SIZE);
        // Draw back face
        drawRectangularFace(g2d, x+CUBE_SIZE/2, y-CUBE_SIZE/2, CUBE_SIZE, CUBE_SIZE);
        // Connect front and back faces
        connectFaces(g2d, x, y, x+CUBE_SIZE/2, y-CUBE_SIZE/2, CUBE_SIZE, CUBE_SIZE);
        
    }
    
    
    // Method to draw a lines
    private void drawLine(Graphics2D g2d, int x1, int y1, int x2, int y2){
        
        g2d.setColor(Color.ORANGE);
        g2d.drawLine(x1, y1, x2, y2);
        
    }
    
    
    // Method to draw a rectangular face
    private void drawRectangularFace(Graphics2D g2d, int x, int y, int width, int height)
    {
        drawLine(g2d, x, y, x+width, y);
        drawLine(g2d, x+width, y, x+width, y+height);
        drawLine(g2d, x+width, y+height, x, y+height);
        drawLine(g2d, x, y+height, x, y);
    }
    
    
    // Method to connect the front and back faces
        private void connectFaces(Graphics2D g2d, int x1, int y1, int x2, int y2, int width, int height)
    {
        drawLine(g2d, x1, y1, x2, y2);
        drawLine(g2d, x1+width, y1, x2+width, y2);
        drawLine(g2d, x1+width, y1+height, x2+width, y2+height);
        drawLine(g2d, x1, y1+height, x2, y2+height);
    }
    
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("3 D Cube");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ThreeDCube());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
}





How to Draw a Cube in Java NetBeans






Java - Shapes Generator Project In Java Netbeans

How to Create a Shape Generator App In Java Netbeans

Java Project Tutorial - How To Create a Geometric Shapes Generator Project In Java Netbeans.


In this Java Tutorial we will see How To Make a Geometric Shapes Generator Project In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create an inner class called DrawingPanel that extends JPanel.
- Create a method to generate random shapes type (e.g., circle, rectangle, triangle), with random values for position, and size.
- Create a method "createRegularPolygon", to create regular polygons like pentagons and hexagons.





Project Source Code:


package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class ShapeGeneratorApp extends JFrame {
    
    private DrawingPanel drawingPanel;
    private JButton generateButton;

    public ShapeGeneratorApp()
    {
        setTitle("Shape Generator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);
        
        // Initialize the drawing panel and the "Generate Shape" button
        drawingPanel = new DrawingPanel();
        generateButton = new JButton("Generate Shape");
        generateButton.setFocusPainted(false);
        generateButton.setBorderPainted(false);
        generateButton.setBackground(new Color(63, 81, 181));
        generateButton.setForeground(Color.white);
        generateButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              // Call the method to generate a random shape
                drawingPanel.generateRandomShape();
                
            }
        });
        
        // Create a panel to hold the button
        JPanel controlPanel = new JPanel();
        controlPanel.add(generateButton);
        
        // Set the layout and add the controls panel and drawing panel to the JFrame
        setLayout(new BorderLayout());
        add(controlPanel, BorderLayout.NORTH);
        add(drawingPanel, BorderLayout.CENTER);
        
    }
    
    // Inner class to handle the drawing panel
    private class DrawingPanel extends JPanel
    {
        private Shape currentShape;
        private Color currentColor;
        
        public DrawingPanel()
        {
            setBackground(Color.WHITE);
            currentColor = Color.BLACK;
        }
        
        // Method to generate a random shape
        public void generateRandomShape()
        {
            
            Random random = new Random();
            // Update the limit to include all shape types
            int ShapeType = random.nextInt(6);
            int x = random.nextInt(getWidth() - 50);
            int y = random.nextInt(getHeight() - 50);
            int size = random.nextInt(100) + 50;
            
            switch (ShapeType)
            {
                
                case 0: // circle
                    currentShape = new Ellipse2D.Double(x,y, size,size);
                    break;
                    
                case 1: // rectangle
                    int width = random.nextInt(100)+50;
                    int height = random.nextInt(100)+50;
                    currentShape = new Rectangle(x,y, width,height);
                    break;
                    
                case 2: // triangle
                    int[] xPoints = {x, x + size / 2, x + size};
                    int[] yPoints = {y + size, y, y + size};
                    currentShape = new Polygon(xPoints, yPoints,3);
                    break;
                    
                case 3: // square
                    currentShape = new Rectangle(x,y, size,size);
                    break;
                   
                case 4: // pentagon
                    currentShape = createRegularPolygon(x,y, size,5);
                    break;
                    
                case 5: // hexagon
                    currentShape = createRegularPolygon(x,y, size,6);
                    break;
            
            }
            
            // create a new color
            currentColor = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
            
            // Repaint the panel to show the newly generated shape
            repaint();        
        }
        
        
        // Method to create a regular polygon
        private Shape createRegularPolygon(int x, int y, int size, int sides)
        {
            GeneralPath path = new GeneralPath();
            double angle = 2 * Math.PI/sides;
            
            path.moveTo(x+size*Math.cos(0), y+size*Math.sin(0));
            
            for(int i = 1; i < sides; i++)
            {
                path.lineTo(x+size*Math.cos(angle*i), y+size*Math.sin(angle*i));
            }
            
            path.closePath();
            return path;
        }
        
        
        @Override
        protected void paintComponent(Graphics g){
            
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            
            // Check if there's a shape to draw
            if(currentShape != null)
            {
                g2d.setColor(currentColor);
                g2d.fill(currentShape);
            }
            
        }
        
    }
    
    
    public static void main(String[] args){
        SwingUtilities.invokeLater(()->{
        
            ShapeGeneratorApp shapeGenerator = new ShapeGeneratorApp();
            shapeGenerator.setVisible(true);
            
        });
    }
    
    
}


The Final Result:

circle

hexagon

pentagon

rectangle

square

triangle