Canvas patterns
Just playing about with <canvas>
by Will Stott
HTML
<form name="frm" action="html_form_action.asp" method="get">
<p>
- Scale: <input type="text" name="scaleVal" value="100"/>
----- Length: <input type="text" name="lengthVal" value="10"/>
</p>
<p> ----- R: <input type="text" name="rVal" value="255"/>
------------ G: <input type="text" name="gVal" value="255"/>
------ B: <input type="text" name="bVal" value="255"/>
</p>
<p> ----- R: <input type="text" name="rbVal" value="0"/>
------------ G: <input type="text" name="gbVal" value="0"/>
------ B: <input type="text" name="bbVal" value="0"/>
</p>
<input type="button" onclick="patThree()" value="Draw!" />
<input type="button" onclick="startAnim()" value="Animate!" />
<input type="button" onclick="stopAnim()" value="Stop!" />
---------------- Frame Length (milliseconds): <input type="text" name="animSpeed" value="150"/>
</form>
<p>
<canvas id="canvas" width="1000" height="600">A HTML5 canvas tag supporting browser will be needed to use this page.</canvas>
</p>
JavaScript
patThree();
var animationOn = false;
function patThree () {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0,0,1000,600);
var r = document.frm.rbVal.value;
var g = document.frm.gbVal.value;
var b = document.frm.bbVal.value;
ctx.fillStyle = "rgba(" + r + "," + g + ","+b+",1)";
ctx.fillRect(0,0,1000,600);
ctx.strokeRect(0,0,1000,600);
var x = 500;
var y = 300;
var incre = document.frm.scaleVal.value;
r = document.frm.rVal.value;
g = document.frm.gVal.value;
b = document.frm.bVal.value;
var length = document.frm.lengthVal.value;
for (i = 0; i <= length; i++) {//Drawing Loop
var colR = Math.floor(Math.random() * r);
var colG = Math.floor(Math.random() * g);
var colB = Math.floor(Math.random() * b);
ctx.strokeStyle = "rgba(" + colR + "," + colG + ","+colB+",1)";
ctx.beginPath();
ctx.moveTo (x, y);
var xdiff = (Math.floor(Math.random() * incre) - (incre/2));
var ydiff = (Math.floor(Math.random() * incre) - (incre/2));
if (Math.random() > 0.5) {
x += xdiff * - 1;
y += ydiff * - 1;
} else {
x += xdiff;
y += ydiff;
}
ctx.lineTo(x, y);
ctx.stroke();
}
}
function animatePattern () {
if (animationOn) {
setTimeout("animatePattern()",document.frm.animSpeed.value);
patThree();
}
}
function startAnim () {
animationOn = true;
animatePattern();
}
function stopAnim () {
animationOn = false;
}