Onclick Function Button Change Canvas
I have the following code creating an animated series of lines in canvas. I would like to change the context being drawn in the canvas depending on certain DOM elements being click
Solution 1:
You just want a click-handler on #click to change your wave colors?
$('#click').on('click',function(){
m = ceil(w/(10*u)) + Math.random()*10*8;
});
Example code and a Demo:
var c = document.querySelector('.c'),
w, h,
ctx = c.getContext('2d'),
x0, y0, x, y,
t = 0, t_step = 1/200,
u = 5, m,
tmp,
ceil = Math.ceil,
exp = Math.exp, pow = Math.pow, sqrt = Math.sqrt,
PI = Math.PI, sin = Math.sin, cos = Math.cos;
var rand = function(max, min) {
var b = (max === 0 || max) ? max : 1, a = min || 0;
return a + (b - a)*Math.random();
};
var trimUnit = function(input_str, unit) {
returnparseInt(input_str.split(unit)[0], 10);
};
var initCanvas = function() {
var s = getComputedStyle(c);
w = c.width = trimUnit(s.width, 'px');
h = c.height = trimUnit(s.height, 'px');
m = ceil(w/(10*u)) + 25;
};
var wave = function () {
ctx.clearRect(0, 0, w, h);
ctx.lineWidth = 2;
for(var i = 0; i < m; i++) {
x0 = -20;
y0 = i*2*u;
ctx.beginPath();
ctx.moveTo(x0, y0);
for(x = 0; x < w; x++) {
y = u*sin(x/6/(16*i/m + 1) - w*(i/m + 1)*t/120) + i*2*u;
ctx.lineTo(x, y);
x0 = x;
y0 = y;
}
ctx.strokeStyle = 'hsl(' + i*360/m + ', 100%, 70%)';
ctx.stroke();
}
t += t_step;
requestAnimationFrame(wave);
};
addEventListener('resize', initCanvas, false);
$('#click').on('click',function(){
m = ceil(w/(10*u)) + Math.random()*10*8;
});
initCanvas();
wave();
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><h4>Click on sun to <br>change wave colors.</h4><canvasclass='c'>waves</canvas><divstyle="width:100%; height:100%; position:absolute; top:0; left:0;"><center><imgid="click"style="margin:0 auto; position:relative; top:35%; width:100px; height:auto;"src="https://dl.dropboxusercontent.com/u/139992952/multple/sunny.png"alt="" ></center>
Post a Comment for "Onclick Function Button Change Canvas"