Jump to content
Search Community

Anim not randomizing when put on canvas

ladlon test
Moderator Tag

Recommended Posts

This was working fine as a non-canvas version, but once I tried it within a Canvas context, it doesn't appear to be randomizing the destination position each cycle like it used to.

 

How would I need to modify the js code in order to have the position randomize each  cycle?  Seems maybe the GSAP tween needs to be moved to another spot in the code?

 

Is everything else in my code looking okay?

See the Pen rNxjLYp by ladlon (@ladlon) on CodePen

Link to comment
Share on other sites

It's working fine, your numbers are just too small to notice a difference. Try this:

x: "random(0,500)", y: "random(0,400)"

Also all of this is useless:

document.addEventListener("DOMContentLoaded", function(event) { 
    window.onload = function() {
        window.requestAnimationFrame(function() {

 

  • Like 1
Link to comment
Share on other sites

Oops.  Yes, you're absoutely correct... It does work, if you put larger numbers in.  My mistake.  Sorry.

 

As for the onload type stuff...  Is it just in the wrong place?  That's code from these forums, I believe... to make sure that things don't start before the assets have loaded in.  I want to be sure to utilize that sort of thing, as I think it's important in my particular case.  Would I instaed put it in the HTML, and have it (when ready) trigger the js file that contains the GSAP animation?

 

Second related question...  In that same sample, I've been trying to do a similar randomized rotation, but I get the impression that works differently in this Canvas context.  I did a standard GSAP tween, much like the one in the demo for the position, except it is targeting the rotation property.

 

First thing is... Would rotation be a property of the IMAGE I define in the sample, or the OBJECT?

 

Looking into it online, I keep seeing samples where it seems the CANVAS itself is being rotated (in response to the question 'how do you rotate in Canvas?)... which is not what I'm after.  I want to just rotate the individual images (randomly).

 

The tween I added is:

 

gsap.to(pic, {rotation: "random(-40,2)", duration: "random(4,8)", yoyo: true, ease:"power1.inOut", repeat: -1, repeatRefresh:true});

... and I added an initial value to the pic.rotation property in the section where I'm defining the object.  I actually tried adding the initial values to both the object and the image item... as well as  targeting both the image and the object in the tween itself, as I'm not sure which it should be.

Link to comment
Share on other sites

Well, I'm using GSAP to animate everything, so that's why I'm asking.

 

So, does that mean GSAP cannot be used to rotate an item on Canvas?  I have to resort to using Canvas's own methods?  If so, my worry is that it won't have the browser support fallbacks that GSAP has built-in (...which is half the reason I switched over to GSAP).

Link to comment
Share on other sites

21 minutes ago, ladlon said:

does that mean GSAP cannot be used to rotate an item on Canvas?

Not directly, that is correct. You could animate a value with GSAP and use that value in an onUpdate or something to rotate an element. But GSAP has no method to directly rotate a canvas object.

 

21 minutes ago, ladlon said:

If so, my worry is that it won't have the browser support fallbacks that GSAP has built-in (...which is half the reason I switched over to GSAP).

If a browser doesn't support the rotation method then it doesn't support canvas at all. Every browser since IE8 (which GSAP doesn't even support) supports canvas.

 

You're worrying about nothing :) 

Link to comment
Share on other sites

The big issue with rotating object by rotating the canvas itself is obviously regarding aligning the Canvas rotation axis with that of the target image item... but, luckily I managed to find a block of code that someone thought up to address that.  If it doesn't work, though, I may just go back to my (working) non-canvas version.

Link to comment
Share on other sites

59 minutes ago, ladlon said:

So, does that mean GSAP cannot be used to rotate an item on Canvas?

 

I've gone over this before. GSAP is not animating canvas. GSAP is animating/updating an object. You take the values of that object and apply to your canvas via draw commands. Canvas draw commands have nothing to do with gsap. Your ticker/draw method should not have anything related to gsap in it. Just vanilla JavaScript.

 

I've already linked to this. Lots of canvas tips.

 

 

 

  • Like 1
Link to comment
Share on other sites

@OSUblake Yes, again, I know.  I'm not trying to animate the Canvas, or grab things on the Canvas and animate them as if they weren't baked into the Canvas... I'm trying to animate an image item that then gets stamped onto the Canvas during each refresh cycle.

 

Where do I have GSAP items in my ticker/draw method???   The code I'm using is actually based on the very code you gave me.

 

How would you do tweening between the neutral 0 degree state and a random rotation amount using non-GSAP methods?

Link to comment
Share on other sites

My post is about how you keep asking general JavaScript and canvas questions. 

 

This is gsap related code.

gsap.to(obj, {
  x: 100
})

 

This is canvas related code. The code inside the ticker function is going to be unique for almost every animation. 

gsap.ticker.add(function() {  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(sub.x, sub.y, 100, 100);
});


I'm willing to help you out, but you have to meet me halfway. Look at everything in this thread. It literally has the answers for you on how to do rotation and other transforms.

https://greensock.com/forums/topic/16501-how-can-i-improve-this-gsap-particle-animation-code/?tab=comments#comment-73821

 

So does the demo I posted above. If you need help understanding my code, just ask which part you don't understand. Take it one step at time.

 

 

 

  • Like 3
Link to comment
Share on other sites

Well, my original (working) version of my site animation was using GSAP and a non-canvas solution (relative positioning, etc).  Worked, but I kept getting told I should use Canvas, so I wanted to try that out, since it would provide a more stable/predictable structure, not requiring hacks and compromises.

 

So, I taught myself that today, and got a working Canvas-based random positional drifting thing happening... but then found out that GSAP won't be able to help me with the random rotation aspect of it.  So, then I pursued the Canvas (non-GSAP) method of doing rotations, but then found out that (apparently) you can only rotate the entire canvas... so some form of calculation of offsets would be needed... which is a bit much to figure out for someone who hasn't done this before.  But, I found some user-designed versions, and tried them out... but, it's been tricky trying to fuse these little bits of code into the existing code I have, as there are so many factors that have to be tweeked/considered... all which surely make sense... if you know what you are doing.

 

I've been watching vids all day, and each has a different system (request animation frame, etc), which just adds to the confusion.  Most of the time, they use shape plotting, rather than images... and it took me quite a while to finally get how to fuse image-based animation and object-based items, as far as accessing parameters in the various routines.

 

I am reading the articles and studying the code samples... but, again, many are not hitting on some of the important things I'm trying to learn.  Your last example (star particle spray) certainly illustrates that rotation on the individual items central axis is possible (...or, at least an offset can be applied to the canvas to simulate it, as shown in most of the examples I've found)... but, (in the case of the star spray), that's just a continuous rotation, as opposed to ping-pong tweening between the neutral rotation state and some random rotation amount... which is a whole other bunch of code, which then has to be properly fused with the existing system.

 

I'm certainly asking Javascript/Canvas questions... but doing so to learn how/what to use in the context of a GSAP-based animation... which is where I was trying to head (until I found out rotations are out, for that).  Now, I'm trying to figure out how to do 'pure' (non-GSAP) rotation of individual items... and would have gone elsewhere (...if I actually knew where best to go...), but you are very knowledgable and eager about Canvas, so it struck me as wise to ask here.

 

 

I'm basically just trying to have an image item randomly rock between a neutral (0 degree) state and a random clockwise or counterclockwise value.  I had it working just easily with the non-canvas, GSAP tween method... but now that I can't use GSAP for the rotation, I'm unclear on how to do rotation tweens without GSAP.  Every example I see usually just uses some mathematically-based constant rotation... and not tweening.  Or, they use older methods for the updating of the Canvas, so I worry that the methods they show might be outdated or even incompatible today.  Again, not being very familiar with this, I do not know the current pitfalls or best methods.

Link to comment
Share on other sites

25 minutes ago, OSUblake said:

This is canvas related code. The code inside the ticker function is going to be unique for almost every animation. 


gsap.ticker.add(function() {  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(sub.x, sub.y, 100, 100);
});

 

 

To further illustrate how this is canvas related code. You don't need to use gsap's ticker. You can do the rAF calls yourself, and it will work the same, although it's recommended to use gsap's ticker.

 

requestAnimationFrame(draw);

function draw() {  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillRect(sub.x, sub.y, 100, 100);
  requestAnimationFrame(draw);
}

 

  • Like 1
Link to comment
Share on other sites

Ya, my code is based on the one you provided for the dog ping-ponging back and forth, as that addressed my question about how to not only animate but address image file properties (...as everything else seemed to be DrawRectangle things, which didn't show how to address an image file).

 

I want to use 'best practices' with this stuff... and I'm certainly nervous about compatibility, etc... as I'm in no position to think up any fallback coding.  That (and because you told me so before) is why I'm using the ticker.  I'm certainly most comfortable using GSAP whenever I can, because I rely on the built-in fallbacks for all the browser quirks etc that may or may not be present.

 

I found this coding in an article which was most likely mentioned deep in one of the threads you linked to.  It (hopefully) will address the whole rotational offset challenge, but I still need to figure out how to then use that with some form of tweening... apparently Canvas-based, since I found out today that GSAP cannot (apparently) address rotation with Canvas-based scenarios.  That's odd, as I would have thought you just do the regular GSAP rotation tween on the image, then stamp it down on the canvas (as you do with GSAP positional tweens).  So, now I'm trying to sort out non-GSAP assisted Canvas rotation tweening.

 

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Non-rotated rectangle
ctx.fillStyle = 'gray';
ctx.fillRect(80, 60, 140, 30);

// Matrix transformation
ctx.translate(150, 75);
ctx.rotate(Math.PI / 2);
ctx.translate(-150, -75);

// Rotated rectangle
ctx.fillStyle = 'red';
ctx.fillRect(80, 60, 140, 30);

But, again, I have to figure out how to utilize this with an image, as opposed to using the FillRect routine.... plus, somehow tween to/from random values.  Easy in GSAP non-Canvas, but  definitely new territory for me within (pure) Canvas.

Link to comment
Share on other sites

1 minute ago, ladlon said:

Worked, but I kept getting told I should use Canvas, so I wanted to try that out, since it would provide a more stable/predictable structure, not requiring hacks and compromises.

 

Don't know why someone would recommend that. I would only recommend canvas if you are having performance issues, like if you're trying to animate hundreds of items, or doing some kind of special effect/image processing.

 

2 minutes ago, ladlon said:

but then found out that GSAP won't be able to help me with the random rotation aspect of it. 

 

It will. You're still having a disconnect between gsap and canvas.

 

9 minutes ago, ladlon said:

So, then I pursued the Canvas (non-GSAP) method of doing rotations, but then found out that (apparently) you can only rotate the entire canvas

 

You're getting bad information from somewhere. Rotation (transforms) is an integral part of canvas. 

 

image.thumb.png.2b9ff8e217a539b81ef3f11e44a82ed5.png

 

 

 

  • Like 3
Link to comment
Share on other sites

2 minutes ago, ladlon said:

 

 


const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Non-rotated rectangle
ctx.fillStyle = 'gray';
ctx.fillRect(80, 60, 140, 30);

// Matrix transformation
ctx.translate(150, 75);
ctx.rotate(Math.PI / 2);
ctx.translate(-150, -75);

// Rotated rectangle
ctx.fillStyle = 'red';
ctx.fillRect(80, 60, 140, 30);

 

All the matrix/transform stuff is the same for an image. Just replace the fillStyle/fillRect calls with drawImage.

 

  • Like 1
Link to comment
Share on other sites

Well, one of the main reasons I wanted to do a complete rebuild of my site animation using Canvas, was that the current method had the 'background image' image (set on relative positioning) serving as the 'stage', and then I had several smaller image files in separate DIVs, set to absolute positioning (so that I could then offset them to go overtop of the 'background' image.... and all the while, everything being responsive within the containing DIV.

 

That worked... and actually looks great... but the position values were kind of haphazard, and the smaller individual image elements would not properly scale 'locked' to the background image... so, a bit of a mess.  Worked, but certainly a house of cards, not to be poked at.  Canvas had the benefit of baking everything into a single canvas, as opposed to a bunch of floating elements that had to be coded to (try and) keep up with the background image.

 

Going the Canvas route also apparently would allow me to also tinker with some of the plugins like PixiPlugin, which might be of use for further work on it (...plus the whole particle thing).

Link to comment
Share on other sites

11 minutes ago, ladlon said:

I still need to figure out how to then use that with some form of tweening... apparently Canvas-based, since I found out today that GSAP cannot (apparently) address rotation with Canvas-based scenarios.  That's odd, as I would have thought you just do the regular GSAP rotation tween on the image, then stamp it down on the canvas (as you do with GSAP positional tweens).  So, now I'm trying to sort out non-GSAP assisted Canvas rotation tweening.

 

Again, you can do rotation. It's just a value.

 

See the Pen a6df91724b67db6b62dfe15c76b4c433 by osublake (@osublake) on CodePen

 

 

Not using gsap, it would look nearly identical, except you have less control.

 

See the Pen ab9579dcaece080b8be502ce34d8fc82 by osublake (@osublake) on CodePen

 

  • Like 3
Link to comment
Share on other sites

Yes, sorry... bad wording.  By it, I meant you rotate the 'property' of the image/object.

 

(Re: Latest rotation sample): Weird!..... but very good news.  I actually tried it (seemingly the exact same way you did), and it didnt' seem to work.  And then when I asked about it, Zack seemed to indicate that GSAP can't directly rotate things... which is why I was then trying to go the non-GSAP rotation route.

 

Ya, I noticed the rotation properties in your previous examples.  Weird, why didn't those show up in any of the vids I saw?  (See, that's what I'm talking about when I say I was concerned about the validity of these YouTube tutorial vids I find!)


Ha!  I'll definitely agree with you that the info I'm getting is sometimes contradictory...  I'm still confused about whether or not to use the whole 'wait for the page to fully load' routine.  You had it in your previous sample to me (Dog sliding), as well as your current one, yet (unless I'm understanding him wrong) Zack seems to think they are unnecessary.  Look at his posts on this thread.  So, ya, I'm a bit confused... and going in circles sometimes.


I'll study up on the whole Canvas rotation thing some more... although now I'm confused about whether that 'move the canvas to line up the origin to the target 'object' origin, rotate the whole canvas, drop the object, rotate the canvas back and move the canvas back' hack/routine is still needed.

Link to comment
Share on other sites

Okay, lots to look over and experiment with.  I'm really glad to see that the rotation is (seemingly) easy, and I don't have to worry about all the hack code methods I've been seeing so far.

 

Hopefully it works over here.  I'll give it a try.   Thanks for the help with that.  Seeing as I can use GSAP, I think I can figure out the random 'rocking back and forth' now.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...