Random Dots

Or a Very Bad Automated van Gogh

Dot size: count:

HTML Code

<html>
<head>
   <script type="text/javascript"
      src="canvasClass2.js">
   </script>
</head>
<body>

<h1>Random Dots</h1>
<h3>Or a Very Bad Automated <a href="https://en.wikipedia.org/wiki/The_Starry_Night">van Gogh</a></h3>


<script>
var canvas1 = new MyCanvas(300, 300);

canvas1.Redraw();
</script>

<p>
Dot size:
<input
      type="text" 
      name="Dot Size"
      maxLength = "3"
      size = "3"
      id="DotSize", onchange="canvas1.ChangeDot('DotSize')">
count:
<input
      type="text" 
      name="dot Count"
      maxLength = "5"
      size = "5"
      id="DotCount", onchange="canvas1.ChangeCount('DotCount')">
<p>

<button type="button" id="Redraw" onclick="canvas1.Redraw()">Redraw</button>

canvasClass2.js

function MyCanvas(width, height) {
    
    if (width == undefined || width < 0) {
           width = 300;
    }
  
    if (height == undefined || height < 0) {
            height = 300;
    }

    var canvas = document.createElement('canvas')
        canvas.height = height;
        canvas.width = width;

    // add it to the document 
    document.body.appendChild(canvas);

    // save some info as local values
    this.width = width;
    this.height = height;
    this.ctx =  canvas.getContext("2d");
    this.dotSize = 1;
    this.dotCount = 100;

    return this;
}

MyCanvas.prototype = {
    ChangeDot:   function(sizeID) {
        var sizeNode  = document.getElementById(sizeID);
	var size = parseInt(sizeNode.value);

        if (size > 0 ) {
	    this.dotSize = size;
	    this.Redraw();
	} 
    },

    ChangeCount: function(countID) {
        var countNode  = document.getElementById(countID);
	var count = parseInt(countNode.value);

        if (count > 1 ) {
	    this.dotCount = count;
	    this.Redraw();
	} 
    },

    Redraw:  function() {
        var i;
        var x,y;
        var r,g,b;
        var color;

        this.ctx.fillStyle="#cccccc";
        this.ctx.fillRect(0,0,this.width,this.height);

        for(i=0;i<this.dotCount;i++) {
            r = Math.floor(Math.random()*255);
            g = Math.floor(Math.random()*255);
            b = Math.floor(Math.random()*255);
            color = "rgb("+r+","+g+","+b+")";
            this.ctx.fillStyle = color;

            x = Math.random()*this.width;
            y = Math.random()*this.height;
            this.ctx.fillRect(x, y, this.dotSize, this.dotSize);
        }
    }
};