Canvas Test ZigZag
Testing some stuff
by joquery
HTML
<canvas id="myCanvas" width="300" height="200"></canvas>
<div>
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="next">Next</button>
<button id="reset">Reset</button>
</div>
CSS
#myCanvas {
background: #fafaee;
}
JavaScript
var context;
var canvas;
var drawInterval = 1000.0 / 30.0;
var duration = 3;
var stepping = 1 / (duration * drawInterval);
var intervalId;
var progress = 0.0;
var draw = function() {
if (progress + stepping > 1) {
progress = 1;
} else {
progress += stepping;
}
context.save();
context.beginPath();
var numberOfSpikes = 8;
var singleSpikeWidth = canvas.width / (numberOfSpikes);
var halfSpikeWidth = singleSpikeWidth / 2;
var singleSpikeHeight = singleSpikeWidth;
// adding the height, cause else it would stop too early
var deltaHeight = ((canvas.height + singleSpikeHeight) / 2) * progress;
var currentHeightTop = canvas.height / 2 - deltaHeight + halfSpikeWidth;
var currentHeightBottom = canvas.height / 2 + deltaHeight + halfSpikeWidth;
context.moveTo(0, currentHeightTop);
for (var i = 0; i < numberOfSpikes; i++) {
var firstSpikePointX = (i * singleSpikeWidth) + (halfSpikeWidth);
var secondSpikePointX = (i * singleSpikeWidth) + (2 * halfSpikeWidth);
context.lineTo(firstSpikePointX, currentHeightTop - singleSpikeHeight);
context.lineTo(secondSpikePointX, currentHeightTop);
}
//context.stroke();
context.lineTo(canvas.width, currentHeightBottom);
for (var j = numberOfSpikes; j > 0; j--) {
var firstSpikePointX = (j * singleSpikeWidth) - (halfSpikeWidth);
var secondSpikePointX = (j * singleSpikeWidth) - (2 * halfSpikeWidth);
context.lineTo(firstSpikePointX, currentHeightBottom - singleSpikeHeight);
context.lineTo(secondSpikePointX, currentHeightBottom);
}
context.closePath();
context.clip();
context.rect(0,0,canvas.width,canvas.height);
context.fillStyle="red";
context.fillRect(0,0,canvas.width,canvas.height);
if (progress === 1) {
clearInterval(intervalId);
}
...