<head> <script type="text/javascript" src="http://mirkwood.cs.edinboro.edu/~bennett/f360/canvasClass.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(200, 200); </script> <p> <script> var canvas2 = new MyCanvas(400, 400); canvas1.Redraw(); canvas2.Redraw(); </script> <p> <button type="button" id="Redraw" onclick="canvas1.Redraw()">Redraw 1</button> <button type="button" id="Redraw" onclick="canvas2.Redraw()">Redraw 2</button> <button type="button" id="Redraw" onclick="canvas2.Redraw(); canvas1.Redraw()">Redraw Both</button>
function MyCanvas(width, height) { // create it var canvas = document.createElement('canvas') canvas.height = height; canvas.width = width; // add it to the document document.body.appendChild(canvas); // save some infor as local values this.width = width; this.height = height; this.ctx = canvas.getContext("2d"); return this; } MyCanvas.prototype.Redraw = function() { var i; var x,y; var r,g,b; var color; this.ctx.fillStyle="#000000"; this.ctx.fillRect(0,0,this.width,this.height); for(i=0;i<100;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, 2, 2); } }