0

I've gotten a lot of help from this site, but I seem to be having a problem putting all of it together. Specifically, in JS, I know how to

a) draw an image onto canvas

b) make a rectangle follow the cursor (Drawing on a canvas) and (http://billmill.org/static/canvastutorial/ball.html)

c) draw a rectangle to use as a background

What I can't figure out is how to use a rectangle as the background, and then draw an image (png) on the canvas and get it to follow the cursor.

What I have so far looks like this:

var canvas = document.getElementByID('canvas');
var ctx = canvas.getContext('2d');
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var bgColor = '#FFFFFF';
var cirColor = '#000000';

clear = function() {
    ctx.clearRect(0, 0, WIDTH, HEIGHT);
}

drawIMG = function(x,y,r) {
    ctx.fillStyle = cirColor;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI*2, true);
    ctx.closePath();
    ctx.fill();
}

draw = function() {
    ctx.fillStyle = bgColor;
    clear();
    ctx.fillRect(0, 0, WIDTH, HEIGHT);
    drawIMG(150, 150, 30);
    drawIMG(300, 500, 12);
};

draw();

This will draw in the HTML5 canvas element, the height and width of which are specified in the HTML and so are variable, with a white rectangle the size of the canvas beneath two black circles at (150,150) and (300,500). It does that perfectly well.

However, I don't know how to also make JS draw a .png on top of that that follows the cursor. Like I said, I've been able to do most of the steps individually, but I have no idea how to combine them. I know, for instance, that I have to do

img = new Image();

and then

img.src = 'myPic.png';

at some point. They need to be combined with position modifiers like

var xPos = pos.clientX;
var yPos = pos.clientY;
ctx.drawImage(img, xPos, yPos);

But I have no idea how to do that while maintaining any of the other things I've written above (specifically the background).

Thanks for your patience if you read through all of that. I have been up for a while and I'm afraid my brain is so fried I wouldn't recognize the answer if it stripped naked and did the Macarena. I would appreciate any help you could possibly send my way, but I think a working example would be best. I am an initiate in the religion of programming and still learn best by shamelessly copying and then modifying.

Either way, you have my optimistic thanks in advance.

1
  • Make a fiddle and I'll try to help.
    – Mosho
    Jun 15, 2014 at 8:06

1 Answer 1

1

First off, I've made an animated purple fire follow the mouse. Click (edit doesn't exist anymore)here to check it out.

Before you continue, I recommend you check out these websites: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

William talks about the basic techniques of canvas animations

http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ Paul Irish talks about a recursive animation function that turns at 60 fps.

Using both of their tutorials is pretty a good start for animation.

Now from my understanding you want one 'background' and one animation that follows the cursor. The first thing you should keep in mind is once you draw on your canvas, whatever you draw on, gets replaced. So the first thing I notice that will cause performance issues is the fact you clear your whole canvas, and not what needs to be cleared.

What you need to do is memorize the position and size of your moving element. It doesn't matter what form it takes because your clearRect() should completely remove it.

Now you're probably asking, what if I draw on the rectangle in the background. Well that will cause a problem. You have two solutions. Either, (a) Clear the background and clear your moving animation and draw them back again in the same order or (b) since you know your background will never move, create a second canvas with position = absolute , z-index = -1 , and it's location the same as the first canvas.

This way you never have to worry about the background and can focus on the animation currently going on.


Now getting back to coding part, the first thing you'll want to do is copy Paul Irish's recursive function:

(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

Question then is, how to use it? If you go here you can check out how it was done:

function fireLoop()
{
    window.requestAnimationFrame(fireLoop);
    fire.update();
    fire.render();
    console.log('you spin me right round baby right round');
    follow();

}

This is the loop I use. Every second Paul Irish's function will call the main loop. In this loop. I update the information choose the right animation that needs to be drawn and then I draw on the canvas (after having removed the previous element).

The follow function is the one that chooses the next coordinates for the animation. You'll have to change this part since, you don't want to move the canvas but move the animation. You can use the same code, but you need to apply location to where you want to draw on the canvas.

function follow()
{
        $(fireCanvas).offset({
            top: getTop(),
            left: getLeft()
        });

}

function getTop()
{
    var off = $(fireCanvas).offset();
    if(off.top != currentMousePos.y - $(fireCanvas).height() + 10)
    {
        if(off.top > currentMousePos.y - $(fireCanvas).height() + 10)
        {
            return off.top - 1;
        }
        else
        {
            return off.top + 1;
        }
    }
}
function getLeft()
{
    var off = $(fireCanvas).offset();
    if(off.left != currentMousePos.x - $(fireCanvas).width()/2)
    {
        if(off.left > currentMousePos.x - $(fireCanvas).width()/2)
        {
            return off.left - 1;
        }
        else
        {
            return off.left + 1;
        }     
    }
}
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
    currentMousePos.x = event.pageX;
    currentMousePos.y = event.pageY;
});

If you want me to go into depth about anything specific let me know.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.