简体   繁体   中英

bezier curve creation dynamically?

I am trying to achieve grass like bend on a straight line created by using Cubic bezier curve .I have created a straight line using Bezier curve and now i want to bend it from top.But the problem I am facing is I am not able to do it dynamically .The moment I use mousemove for creating the bend,series of curves appear giving the canvas a paint like look which is somthing I dont want.I just want a single curved line.My question is how do I clear the previous lines that have been drawn and restore the latest bended curve?? My CODE: here is my code if you want to have a look at it

Create two canvases stacked on top of each other:

The first one containing the static content, the other only the dynamic content.

This way you will only need to be concerned about clearing the area the grass was drawn in (and this is much faster too as there is no need to redraw static all the time).

Place the two canvases inside a div which have position set to relative, then place the canvases using position set to absolute.

Now you can make a function to draw the static content (you will need to redraw it if the browser window gets resized etc.).

Record the area the grass is drawn within and clear only this (for each grass) in the next frame.

If this last is too complicated, just use a simple clear on the "dynamic" canvas:

ctxDyn.clear(0, 0, canvasDyn.width, canvasDyn.height);

This will also preserve transparency of this canvas, or "layer" if you like.

Use requestAnimationFrame to do the actual animation.

var isPlaying = true;

function animate() {

    ctxDyn.clear(0, 0, canvasDyn.width, canvasDyn.height);

    drawGrass(); //function to draw the actual grass

    if (isPlaying) requestAnimationFrame(animate);
}

animate(); // start

The isPlaying is a flag you can toggle with a button on screen or something similar, to be able to stop the animation. See the link for requestAnimationFrame on how to make this cross-browser as this is still a "young" implementation.

dynCtx and dynCanvas can of course be called what you want.

You need to erase the current contents of the canvas before redrawing your updated "grass". This would involve redrawing everything else that is "static" on the canvas. For example:

function redraw() {
  // Erase the current contents
  ctx.fillStyle = 'white';
  ctx.fill(0, 0, canvas.width, canvas.height);

  // Draw the stuff that does not change from frame to frame
  drawStaticContent();

  // Draw the dynamic content
  drawGrass();
}

In your mousemove event, update your grass curve information, then 'redraw'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM