简体   繁体   中英

Canvas clearRect not working using Animate

I am using a animate drawing lines technique to create lines between each of my points. Once a point is activated I want an old point to be removed. I set clearRect outside of my interval but its not removing the old line. In my previous code (before the setInterval was created) worked flawlessly, since adding the setinterval, not so much.

Here is the script for just the clear / creation. Thank you for your help.

function draw(st,en){
            var c = document.getElementById("map_id");
            var ctx = c.getContext("2d");
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.translate(0.5, 0.5);
            var amount = 0;
  
            setInterval(function() {
                amount += 0.05; // change to alter duration
                  if (amount > 1) amount = 1;
                  ctx.clearRect(0, 0, c.width, c.height);
                  ctx.strokeStyle = "#ccc";
                  ctx.moveTo(st['x'], st['y']);
                  ctx.lineWidth = 5;
                  // lerp : a  + (b - a) * f
                  ctx.lineTo(st['x'] + (en['x'] - st['x']) * amount, st['y'] + (en['y'] - st['y']) * amount);
                  ctx.stroke();
            }, 30);
        }

UPDATE **** I found a post regarding my issue. It says I need to include beginPath. I did so, but now I am getting flicker of my lines which means the setInterval is not stopping once it is complete.

So checking for completion of drawn line to unset the interval is the solution. Almost there.

Have the solution to my issue.

I tracked the var amount to determine when it has reached 1 with if ( amount == 1) window.clearInterval(map_int)

Problem solved! See solution below

function draw(st,en){
            var c = document.getElementById("map_id");
            var ctx = c.getContext("2d");
            ctx.clearRect(0, 0, c.width, c.height);
            ctx.translate(0.5, 0.5);
            var amount = 0;
  
            let map_int = setInterval(function() {
                amount += 0.05; // change to alter duration
                  if (amount > 1) amount = 1;
                  ctx.beginPath();
                  ctx.clearRect(0, 0, c.width, c.height);
                  ctx.strokeStyle = "#ccc";
                  ctx.moveTo(st['x'], st['y']);
                  ctx.lineWidth = 5;
                  // lerp : a  + (b - a) * f
                  ctx.lineTo(st['x'] + (en['x'] - st['x']) * amount, st['y'] + (en['y'] - st['y']) * amount);
                  ctx.stroke();
                  if(amount == 1) window.clearInterval(map_int);
            }, 15);
        }

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