/**
* set Canvas
*/
var canvas, cxt;
(function() {
canvas = $('#canvas');
cxt = canvas.get(0).getContext('2d');
}());
/**
* draw text
*/
canvas.click(function(e) {
var pos;
// to do error check
// draw text
pos = getMousePosition(e, canvas.get(0));
drawText(pos);
});
function drawText(pos) {
var text, size, color;
text = $('#text').val();
size = $('#size').val();
color = $('#color').val();
text = (text === '') ? 'Example' : text;
color = (color === '') ? '#000' : color;
size = (size === '') ? '14px' : parseInt(size, 10) + 'px';
cxt.clearRect(0, 0, canvas.width, canvas.height);
cxt.font = size + ' "sans-serif"';
cxt.fillStyle = color;
cxt.fillText(text, pos.x, pos.y);
}
// get mouse click position
function getMousePosition(mouseEvent, targetCanvas) {
var x, y;
if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
x = mouseEvent.pageX;
y = mouseEvent.pageY;
} else {
x = mouseEvent.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = mouseEvent.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
return {
x: x - targetCanvas.offsetLeft,
y: y - targetCanvas.offsetTop
};
}
// clear canvas text
$('#clear button').click(function() {
cxt.clearRect(0, 0, canvas.width(), canvas.height());
})
<p id="tool">
Text: <input id="text" name="text" type="text" value="Example"> |
Size: <input id="size" name="size" type="text" size="3" value="14"> |
Color: <input id="color" name="color" type="text" size="7" value="#000">
</p>
<canvas id="canvas" name="canvas" width="200" height="200"></canvas>
<p id="clear"><button>Clear</button>
#tool {
margin: 20px 20px 10px;
}
#canvas {
margin: 10px 20px;
border: 2px dotted #DDD;
}
#clear {
margin: 10px 20px;
}