Draw Circles on Canvas

No CSS

by brouser

HTML

<div id="canvas">Click and hold left mouse button to draw<br/></div>

CSS

canvas {
  border: 3px solid orange;
}

JavaScript

(function() {
    // Creates a new canvas element and appends it as a child
    // to the parent element, and returns the reference to
    // the newly created canvas element


    function createCanvas(parent, width, height) {
        var canvas = {};
        canvas = document.createElement("canvas");
        canvas.context = canvas.getContext("2d");
        canvas.width = width || 100;
        canvas.height = height || 100;
        parent.appendChild(canvas);
        return canvas;
    }

    function init(container, width, height, fillColor) {
        var canvas = createCanvas(container, width, height);
        var ctx = canvas.context;
        // define a custom fillCircle method
        ctx.fillCircle = function(x, y, radius, fillColor) {
            this.fillStyle = fillColor;
            this.beginPath();
            this.moveTo(x, y);
            this.arc(x, y, radius, 0, Math.PI * 2, false);
            this.fill();
        };
        ctx.clearTo = function(fillColor) {
            ctx.fillStyle = fillColor;
            ctx.fillRect(0, 0, width, height);
        };
        ctx.clearTo(fillColor || "#ddd");

        // bind mouse events
        canvas.onmousemove = function(e) {
            if (!canvas.isDrawing) {
               return;
            }
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            var radius = 10; // or whatever
            var fillColor = "#ff0000";
            ctx.fillCircle(x, y, radius, fillColor);
        };
        canvas.onmousedown = function(e) {
            canvas.isDrawing = true;
        };
        canvas.onmouseup = function(e) {
            canvas.isDrawing = false;
        };
    }

    var container = document.getElementById("canvas");
    init(container, 300, 300, "#ddd");

})();