Veryjackson
Veryjackson

Reputation: 25

How can I change canvas with click function?

This is my demo jsFiddle

HTML

<canvas id="random"></canvas>

jQuery

function Random() {
    var length = 9,
        charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }
    return retVal;
}
var ctx = document.getElementById("random").getContext('2d');
ctx.font = "30px Codystar";
ctx.fillText(Random(), 30, 30);
$("#random").click(function () {
    ctx.fillText(Random(), 30, 30);
});

My Question 1-font does not work the first boot and 2-click function does not work ?

Upvotes: 0

Views: 63

Answers (2)

Alvaro
Alvaro

Reputation: 41595

It seems that you have to use the function clearRect(x,y, w, h); to clear the canvas before writing on it again.

Something like:

$("#random").click(function () {
    ctx.clearRect ( 0,0,1000,1000 );
    ctx.fillText(Random(), 30, 30);
});

Living demo: http://jsfiddle.net/vEEPS/3/

Upvotes: 1

Sharad
Sharad

Reputation: 743

I went through following link

and found that it can help you to understand the click functionality on canvas.

Upvotes: 0

Related Questions