[英]Canvas clearRect not working using Animate
我正在使用動畫繪制線條技術在我的每個點之間創建線條。 激活一個點后,我希望刪除一個舊點。 我在間隔之外設置了 clearRect 但它沒有刪除舊行。 在我之前的代碼中(在創建 setInterval 之前)工作完美,因為添加了 setinterval,並沒有那么多。
這是用於清除/創建的腳本。 謝謝您的幫助。
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);
}
更新 **** 我發現了一篇關於我的問題的帖子。 它說我需要包含 beginPath。 我這樣做了,但現在我的線條閃爍,這意味着 setInterval 一旦完成就不會停止。
因此,檢查繪制線是否完成以取消設置間隔是解決方案。 差不多好了。
有我的問題的解決方案。
我使用 if ( amount == 1) window.clearInterval(map_int) 跟蹤 var 數量以確定它何時達到 1
問題解決了! 請參閱下面的解決方案
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.