0

I am trying to create an HTML5 canvas which displays text and onmouseover will remove that text and display a different bit of text.

This works fine for changing the colour - essentially just creating a new canvas over the current one.

However, onmouseover the new text displays but the previous text remains.

http://jsfiddle.net/3j2b2egb/

HTML:

<body onload="changeBack()">
    <canvas id="test" 
            width="330" 
            height="200" 
            style="border:1px solid  #787878;" 
            onmouseover="change()" 
            onmouseout="changeBack()">
    </canvas>

Javascript:

function changeBack() {
    var c = document.getElementById("test");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.font = "bold 16px Arial";
    ctx.fillText("hello", 100, 100);
}

function change() {
    var c = document.getElementById("test");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.font = "bold 16px Arial";
    ctx.fillText("world", 100, 100);
}
augustoccesar
  • 658
  • 9
  • 30
joshnik
  • 438
  • 1
  • 5
  • 15

1 Answers1

0

Try this. I have cleared canvas before drawing it.

function changeBack() {
    var c = document.getElementById("test");
    var ctx = c.getContext("2d");
     ctx.clearRect ( 0 , 0 , c.width, c.height );
    ctx.fillStyle = "blue";
    ctx.font = "bold 16px Arial";
    ctx.fillText("hello", 100, 100);
}


function change() {

    var c = document.getElementById("test");
    var ctx = c.getContext("2d");
    ctx.clearRect ( 0 , 0 , c.width, c.height );
    ctx.fillStyle = "red";
    ctx.font = "bold 16px Arial";
    ctx.fillText("world", 100, 100);

}

Here is working demo http://jsfiddle.net/3j2b2egb/1/

Ankush Jain
  • 5,654
  • 4
  • 32
  • 57