DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Languages
  4. HTML5 canvas – Creating Your Own Paint Program

HTML5 canvas – Creating Your Own Paint Program

Andrey Prikaznov user avatar by
Andrey Prikaznov
·
Oct. 30, 11 · Interview
Like (0)
Save
Tweet
Share
9.51K Views

Join the DZone community and get the full member experience.

Join For Free
Here's a new and interesting article about canvases in HTML5 – I will show you how you can create a nice and simple Paint program. The main idea is to draw a color picker area (rainbow gradient), and load some images to another canvas (here we will draw with selected colors).

Here is the demo and downloadable package:

Live Demo
download in package

Ok, download the source files and lets start coding !


Step 1. HTML

Here is the html code for our Paint:

index.html

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>HTML5 canvas - Creating own Paint program | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />

        <script src="js/jquery-1.5.2.min.js"></script>
        <script src="js/script.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="column1">
                <canvas id="color" width="500" height="128"></canvas>
                <canvas id="panel" width="500" height="333"></canvas>
            </div>
            <div class="column2">
                <div><input type="button" value="Next image" id="swImage" /></div>
                <div>Preview:</div>
                <div id="preview"></div>
                <div id="pick"></div>
                <div>Color:</div>
                <div>RGB: <input type="text" id="rgbVal" /></div>
                <hr />
            </div>
            <div style="clear:both;"></div>
        </div>
        <footer>
            <h2>HTML5 canvas - Creating own Paint program</h2>
            <a href="http://www.script-tutorials.com/html5-canvas-creating-own-paint-program/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </footer>
    </body>
</html>

Step 2. CSS

Here are used CSS styles

css/main.css

/* general styles */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#bababa;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}
footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}
.container {
    color:#000;
    margin:20px auto;
    position:relative;
    width:730px;
}

/* custom styles */
.column1 {
    float:left;
    width:500px;
}
.column2 {
    float:left;
    padding-left:20px;
    width:170px;
}
#panel {
    border:1px #000 solid;
    box-shadow:4px 6px 6px #444444;
    cursor:crosshair;
}
#color {
    border:1px #000 solid;
    box-shadow:0px 4px 6px #444444;
    cursor:crosshair;
}
.column2 > div {
    margin-bottom:10px;
}
#swImage {
    border:1px #000 solid;
    box-shadow:2px 3px 3px #444444;
    cursor:pointer;
    height:25px;
    line-height:25px;

    border-radius:3px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
#swImage:hover {
    margin-left:2px;
}
#preview, #pick {
    border:1px #000 solid;
    box-shadow:2px 3px 3px #444444;
    height:40px;
    width:80px;

    border-radius:3px;
    -moz-border-radius:3px;
    -webkit-border-radius:3px;
}
.column2 input[type=text] {
    float:right;
    width:110px;
}

Step 3. JS

js/script.js

var canvas;
var canvasColor;
var ctx;
var ctxColor;
var bMouseDown = false;
var selColorR = 0;
var selColorG = 0;
var selColorB = 0;

var images = [ // predefined array of used images
    'images/pic1.jpg',
    'images/pic2.jpg',
    'images/pic3.jpg',
    'images/pic4.jpg',
    'images/pic5.jpg'
];
var iActiveImage = 0;

$(function(){

    // drawing active image
    var image = new Image();
    image.onload = function () {
        ctx.drawImage(image, 0, 0, image.width, image.height); // draw the image on the canvas
    }
    image.src = images[iActiveImage];

    // creating canvas objects
    canvas = document.getElementById('panel');
    ctx = canvas.getContext('2d');

    canvasColor = document.getElementById('color');
    ctxColor = canvasColor.getContext('2d');

    drawGradients(ctxColor);

    $('#color').mousemove(function(e) { // mouse move handler
        var canvasOffset = $(canvasColor).offset();
        var canvasX = Math.floor(e.pageX - canvasOffset.left);
        var canvasY = Math.floor(e.pageY - canvasOffset.top);

        var imageData = ctxColor.getImageData(canvasX, canvasY, 1, 1);
        var pixel = imageData.data;

        var pixelColor = "rgba("+pixel[0]+", "+pixel[1]+", "+pixel[2]+", "+pixel[3]+")";
        $('#preview').css('backgroundColor', pixelColor);
    });

    $('#color').click(function(e) { // mouse click handler
        var canvasOffset = $(canvasColor).offset();
        var canvasX = Math.floor(e.pageX - canvasOffset.left);
        var canvasY = Math.floor(e.pageY - canvasOffset.top);

        var imageData = ctxColor.getImageData(canvasX, canvasY, 1, 1);
        var pixel = imageData.data;

        $('#rgbVal').val(pixel[0]+','+pixel[1]+','+pixel[2]);

        var pixelColor = "rgba("+pixel[0]+", "+pixel[1]+", "+pixel[2]+", "+pixel[3]+")";
        $('#pick').css('backgroundColor', pixelColor);

        selColorR = pixel[0];
        selColorG = pixel[1];
        selColorB = pixel[2];
    }); 

    $('#panel').mousedown(function(e) { // mouse down handler
        bMouseDown = true;
    });
    $('#panel').mouseup(function(e) { // mouse up handler
        bMouseDown = false;
    });
    $('#panel').mousemove(function(e) { // mouse move handler
        if (bMouseDown) {
            var canvasOffset = $(canvas).offset();
            var canvasX = Math.floor(e.pageX - canvasOffset.left);
            var canvasY = Math.floor(e.pageY - canvasOffset.top);

            var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
            var pixel = imageData.data;
            pixel[0] = selColorR;     // Red
            pixel[1] = selColorG;   // Green
            pixel[2] = selColorB;   // Blue
            pixel[3] = 255; // Alpha channel  

            ctx.putImageData(imageData, canvasX, canvasY);
        }
    });

    $('#swImage').click(function(e) { // switching images
        iActiveImage++;
        if (iActiveImage >= 10) iActiveImage = 0;
        image.src = images[iActiveImage];
    });
});

function drawGradients() {
    var grad = ctxColor.createLinearGradient(20, 0, canvasColor.width - 20, 0);
    grad.addColorStop(0, 'red');
    grad.addColorStop(1 / 6, 'orange');
    grad.addColorStop(2 / 6, 'yellow');
    grad.addColorStop(3 / 6, 'green')
    grad.addColorStop(4 / 6, 'aqua');
    grad.addColorStop(5 / 6, 'blue');
    grad.addColorStop(1, 'purple');
    ctxColor.fillStyle=grad;
    ctxColor.fillRect(0, 0, canvasColor.width, canvasColor.height);
}

Firstly, notice that now we have 2 canvases. One canvas will be for images, the second one is for canvasColor – for the color picker area. I created a separated function to draw rainbow gradients: drawGradients. Then I added mouse event handlers. And when we click on our second canvas (color picker) – we save the selected color.  When we drag our image – we will ‘draw’ on the first canvas. Now our HTML5 Paint application ready!


Live Demo
download in package


Conclusion

Hope that today`s lesson was interesting for you. We made another one nice html5 sample. I will be glad to see your thanks and comments. Good luck!


Source: http://www.script-tutorials.com/html5-canvas-creating-your-own-paint-program/

HTML

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Cloud Performance Engineering
  • Fargate vs. Lambda: The Battle of the Future
  • gRPC on the Client Side
  • Container Security: Don't Let Your Guard Down

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: