View Full Version : How to clear text on HTML 5 Canvas

11-23-2012, 07:58 AM
Seriously, HTML 5 Canvas really lacks functionality. I searched how to clear a text written on it, and all what I am getting is to clear the whole damn canvas. Moreover, clearing all itself is not working. Here are my codes:


<img src="jjj.jpg" width="252" height="144" id="image">
<canvas id="canvas" width="252" height="144"></canvas>
<input type="button" onClick=" insertImg ();">
<input type="text" id="text"/>
<input type="button" onClick="writeText();">
<input type="button" value="Clear" onClick="clearCanvas();">


//Draw image

function insertImg () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = document.getElementById("image");
context.drawImage(image, 0, 0);

//Write text

function writeText () {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var style = 'italic';
var size = '50pt';
var family = '"Arial Black", Gadget, sans-serif'
var text = document.getElementById("text").value;
context.font = style + " " + size + " " + family;
context.fillStyle = 'blue';
context.fillText(text, 50, 50);

//Clear canvas

function clearCanvas () {
context.clearRect(0, 0, 252, 144);

Everything is working correctly, except, the canvas is not clearing when I click on the clear button. I will be glad if we can clear the text also separately from clearing canvas as a whole.

11-23-2012, 08:10 AM
The problem is that you didn't define "context" for clearCanvas(). If you add the first two lines of the other functions it should work.

11-23-2012, 09:04 AM
holy cow you are right. im learning canvas more since yesterday, so im not used at it too much. thank you for helping me since yesterday. by the way, if i want to clear only the text, can i in canvas?

11-23-2012, 09:17 AM
You could use a "canvas framework" like Rafael.js or kinetic.js or processing.js. Those frameworks often introduce an object model to the canvas with which you can (or rather "seem to be able to") manipulate single objects on your canvas. Internally, though, they will still redraw the whole canvas.

This currently cannot be circumvented because a canvas is nothing more than a pixel based drawing element. One pixel can only have one state, so there are no layers or similar.

11-23-2012, 10:18 AM
damn, i knew it its lame... wish W3C ameliorates it but its too late now as HTML5 is going to be standard soon. Useless feature!

11-23-2012, 08:14 PM
Can you tel me how this website is writing on the the card? Is it canvas?