Nayshal Kerai
Nayshal Kerai

Reputation: 35

change text on mouseclick canvas

I currently have text showing "free space" with a hover saying "click here to reserve bike". When user clicks on the canvas the colour changes to red but how do I make it so the text changes from "click here to reserve bike" to "bike reserved".

This is the code https://jsfiddle.net/nayshal/j2y7jm4t/

<div id="canvas-wrap">
  <canvas id="canvas" width=150 height=100> </canvas>
    <p class="text">Click here to reserve bike</p>
    <p class="text1">Free Space</p>
<div id="overlay"></div>
</div>


var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.rect(0, 0, 180, 100);
ctx.stroke();
ctx.fillStyle = "green";
ctx.fill();

document.addEventListener('click',mouseClick,false);
function mouseClick(e)
{  
ctx.fillStyle = "#FF0000";
ctx.fill();

}

Upvotes: 2

Views: 214

Answers (2)

does_not_compute
does_not_compute

Reputation: 476

Inside your mouseClick event you will need to access the DOM element which contains the "click here to reserve bike" text.

document.getElementByClassName('text').innerHTML = "bike reserved"

will achieve what you are after, I suggest using an ID though (Single use identifier, Rather than classes which can be shared among elements)

e/ - Also I believe you are probably using canvas the wrong way, a <p> tag is a html element and NOT part of a canvas, If you wish to draw text into the canvas read about it here : http://www.w3schools.com/canvas/canvas_text.asp

Upvotes: 0

MortenMoulder
MortenMoulder

Reputation: 6648

What you have going on makes no sense in my mind. You do not add text on top of the canvas using HTML! You should add that using Javascript like this:

ctx.font = "30px Verdana";
ctx.fillText("Hello World", 10, 50);

Otherwise there is no point using a canvas. If you want to change the text after doing that, you need to basically remove everything and set it again, because fillText() 'plants' the text on the canvas. Making it stick. It's not an object you can edit, therefore you need to flush it and create the new text.

https://jsfiddle.net/j2y7jm4t/2/

ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.fillStyle = "#000";
ctx.font = "20px Arial";
ctx.textAlign = 'center';
ctx.fillText("Bike reserved", 75, 50);

Does that make sense?


Now in order to change the text, you would do something like this:

https://jsfiddle.net/j2y7jm4t/3/

Start by setting your text as default:

ctx.fillStyle = "#000";
ctx.font = "12px Arial";
ctx.textAlign = 'center';
ctx.fillText("Click here to reserve bike", 75, 50);

Now it will say

Click here to reserve bike

Then simply go back add whatever you need to do in the click function as you can see here:

ctx.fillStyle = "#FF0000";
ctx.fill();
ctx.fillStyle = "#000";
ctx.fillText("Bike reserved", 75, 50);

Works yeah?

Upvotes: 1

Related Questions