Reputation: 151
This is a simple code to animate a line of text in a canvas but when I use clearRect
it still remains on the canvas and doesn't get erased.
Here is the WebApp:
<title>Error Clearing FillText</title>
<script type="text/javascript">
var c, ctx, episode;
var map01 = "Overgrown...", map02 = "Flood Zone...";
function load() {
c = document.getElementById("canvas");
ctx = c.getContext("2d");
episode = document.getElementById("episode");
ctx.clearRect(0, 0, 400, 240);
ctx.drawImage(episode, 10, 5);
ctx.font = "20px san-serif";
ctx.fillStyle = "white";
}
var nameCharCount1 = 0, nameCharCount2 = 0;
function funcMap01() {
ctx.clearRect(0, 0, 400, 240);
ctx.drawImage(episode, 10, 5);
setInterval('loadMap01()', 70);
}
function funcMap02() {
ctx.clearRect(0, 0, 400, 240);
ctx.drawImage(episode, 10, 5);
setInterval('loadMap02()', 70);
}
function loadMap01() {
nameCharCount1++;
var text = map01.substring(0, nameCharCount1);
ctx.setFillStyle = "0";
ctx.fillText(text, 16, 25);
}
function loadMap02() {
nameCharCount2++;
var text = map02.substring(0, nameCharCount2);
ctx.setFillStyle = "0";
ctx.fillText(text, 16, 25);
}
addEventListener("load", load, false);
</script>
</head>
<body>
<canvas id="canvas" width="400" height="240" style="border: 1px solid #000000;">
</canvas>
<br>
<button onclick="funcMap01();">Overgrown...</button>
<button onclick="funcMap02();">Flood Zone...</button>
<h1>I hate arrays..</h1>
</body>
<img id="episode" src="http://i717.photobucket.com/albums/ww176/T3ZTAM3NT/Episode_zps4fa66a1b.png" style="display: none;">
Do you have any tips/ideas on how should I go about clearing the text?
Upvotes: 1
Views: 1480
Reputation: 1594
I made a fiddle for it so check this out:
And below is the edited code. All I did is cleared the first functions interval in the second functions call and viceversa.
Script
var c, ctx, episode;
var map01 = "Overgrown...", map02 = "Flood Zone...";
var interval1,interval2;
function load() {
c = document.getElementById("canvas");
ctx = c.getContext("2d");
episode = document.getElementById("episode");
ctx.clearRect(0, 0, 400, 240);
ctx.drawImage(episode, 10, 5);
ctx.font = "20px san-serif";
ctx.fillStyle = "white";
}
var nameCharCount1 = 0, nameCharCount2 = 0;
function funcMap01() {
clearInterval(interval2);
ctx.clearRect(0, 0, 400, 240);
ctx.drawImage(episode, 10, 5);
interval1=setInterval('loadMap01()', 70);
}
function funcMap02() {
clearInterval(interval1);
ctx.clearRect(0, 0, 400, 240);
ctx.drawImage(episode, 10, 5);
interval2=setInterval('loadMap02()', 70);
}
function loadMap01() {
nameCharCount1++;
var text = map01.substring(0, nameCharCount1);
ctx.setFillStyle = "0";
ctx.fillText(text, 16, 25);
}
function loadMap02() {
nameCharCount2++;
var text = map02.substring(0, nameCharCount2);
ctx.setFillStyle = "0";
ctx.fillText(text, 16, 25);
}
addEventListener("load", load, false);
Upvotes: 3