Home |  Electronics |  Toolbox |  Gini and Karl's world |  E-cards |  Photos |  Online-Shop


story time | science club | math blog | computer corner  |  penguin page | home

Circle paint

Move the mouse over the canvas to draw random circles (or click with your fingers on the ipad)



And here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>

<script  src="http://code.jquery.com/jquery-1.8.0.min.js">
</script>

<script type="text/javascript"></script>
</head>

<body>

<h2> circle paint </h2>
<h3>Move the mouse over the canvas to draw random circles</h3>

<canvas id="myCanvas" width="700" height="500" style="border:5px solid blue;">
</canvas> 

<script>
var c=document.getElementById("myCanvas");
var ccircle=c.getContext("2d");

$(document).ready(function(){
	$("#myCanvas").click(function(e) {
		/* I get the position of the mouse click */
		var p = $("#myCanvas").offset();
		/* here the circle is drawn, */
		/* I call the function changecolor and createsize */ 
		/*to get a random color  and a random size of the circle, */ 
		/* I also create a random line width through createsize, */ 
		/* ccicrcle.stroke() prints the circle on the canvas */
		ccircle.beginPath();
		newsize = createsize(25, 101); 
		ccircle.arc(e.pageX,e.pageY-p.top,newsize,0,Math.PI*2,true);
		newcolor = changecolor();
		ccircle.strokeStyle=newcolor;
		ccircle.lineWidth = createsize(2, 15);
		ccircle.stroke();
		ccircle.closePath();
		
	});
	
	$("#myCanvas").mousemove(function(e) {
		/* this works like above, it just deals with mousemoves instead of mouse clicks */
	
		var p = $("#myCanvas").offset();
		
		ccircle.beginPath();
		newsize = createsize(25, 101); 
		ccircle.arc(e.pageX,e.pageY-p.top,newsize,0,Math.PI*2,true);
		newcolor = changecolor();
		ccircle.strokeStyle=newcolor;
		ccircle.lineWidth = createsize(2, 15);
		ccircle.stroke();
		ccircle.closePath();
		
	});
	
	/* The array possiblevals contains the possible single inputs for the random color */
	/* which consists of 6 of these values randomly put together */
	var possiblevals = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];

	function changecolor(){
		var newlycreatedcolor = "#";
		for (i=0; i<6;i++){
		var randomnumber=Math.floor(Math.random()*(possiblevals.length));
		newlycreatedcolor = newlycreatedcolor + possiblevals[randomnumber];
		}
		return newlycreatedcolor;

	}


	function createsize(from, to){
		var newsize=Math.floor(Math.random()*to)+ from;
		return newsize;
	}	
	
});
</script>
</body>
</html>
To get the version where you need to click with the mouse to draw a circle, simply delete the mousemove function from the code.

Copyright © 2004-2017 Katja Socher, tuxgraphics.org