Question

here is my site:

I'm trying to get the CD to slowly stop spinning or slowly start up again when I click a button or press the spacebar, but setTimeout() hasn't worked for me.

Thanks.

Below is the js in my body.

var diskCenter = [480, 480];
var disk = new Image;
disk.src = 'disk.jpg';
window.onload = function () {
    var ang = 0;
    var c = document.getElementsByTagName('canvas')[0];
    var ctx = c.getContext('2d');
    setInterval(function () {
        ctx.save();
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.translate(c.width, 0);
        ctx.rotate(Math.PI / 180 * (ang += 5));
        ctx.drawImage(disk, -diskCenter[0], -diskCenter[1]);
        ctx.restore();
    }, 25);
};
Was it helpful?

Solution 2

You will have to use clearInterval() function for stopping your CD. Since you have rotated the CD using setInterval().

Here you go.

HTML :

Include a link :

Stop

Javascript : I am using Jquery here. So include :

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

            var my = setInterval(function(){
                ctx.save();
                ctx.clearRect( 0 , 0, c.width, c.height );
                ctx.translate( c.width , 0 );
                ctx.rotate(Math.PI / 180 * (ang += 5));
                ctx.drawImage( disk, -diskCenter[0], -diskCenter[1] );
                    ctx.restore();

            },25);     

        $(document).ready(function(){
            $("#stop").click(function(e){
                e.preventDefault();
                window.clearInterval(my);
            });
        });

I believe it will make sense.

OTHER TIPS

Here's the code I used to get it to work (I have two buttons, one that slows down the animation (and reverses it) and one that speeds it up:

(function ($) {

    var ang = 0;
    var speed = 5;
    var minSpeed = -10;
    var maxSpeed = 10;
    var c = $('#discCanvas')[0];
    var ctx = c.getContext('2d');

    var diskCenter = [480, 480];
    var disk = new Image;
    disk.src = 'http://swellgarfo.com/9/disk.jpg';


    $(function () {
        setInterval(function () {
            ctx.save();
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.translate(c.width, 0);
            ctx.rotate(Math.PI / 180 * (ang += speed));
            ctx.drawImage(disk, -diskCenter[0], -diskCenter[1]);
            ctx.restore();
        }, 25);
    });

    $('#slowButton').on('click', function () {
        speed = Math.max(minSpeed, speed - 1);
    });

    $('#fastButton').on('click', function () {
        speed = Math.min(maxSpeed, speed + 1);
    });
})(jQuery);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top