var cv = document.getElementById(‘cv’);
var ctx = cv.getContext(‘2d’);
var rect = cv.getBoundingClientRect();
function TextArea(x,y,l,fnt,s ) {
this.x = x; this.y = y ; this.l = l;
this.fnt = fnt; this.s = s;
this.w = 0; this.imageData32 = null;
}
TextArea.prototype.draw = function(col) {
// get text width
ctx.font = this.s + 'px ’ + this.fnt;
this.w = ctx.measureText(this.l).width;
// create temp canvas
var ncv=document.createElement(‘canvas’);
ncv.width= this.w ; ncv.height = this.s;
var nctx = ncv.getContext(‘2d’);
// draw text on temp canvas
nctx.textBaseline=“top”;
nctx.font = ctx.font;
nctx.fillStyle = col || ‘#000’ ;
nctx.fillText(this.l, 0, 0);
// retrieve canvas content as a 32bit array.
this.imageData32 = new Int32Array(nctx.getImageData(0,0,this.w,this.s).data.buffer);
// draw letter
ctx.drawImage(ncv, this.x, this.y);
}
TextArea.prototype.Intersects = function(x,y) {
// BBox testing
if ((x<this.x)||(x>=this.x+this.w)) return false;
if ((y<this.y)||(y>t=his.y+this.s)) return false;
// pixel testing
x-=this.x; y-=this.y; // coordinates within temp canvas
return (this.imageData32[Math.floor( x + y * this.w) ]!=0);
}
// a few examples
var allTexts = [];
allTexts.push( new TextArea(10,50, ‘h’, ‘Arial’, 20));
allTexts.push( new TextArea(80,150, ‘w’, ‘Tahoma’, 22));
allTexts.push( new TextArea(110,300, ‘L’,‘Arial’, 62));
allTexts.push( new TextArea(110,300, ‘L’,‘Dopejam
’, 62));
allTexts.forEach(function(txt) { txt.draw(); } );
// set letter in red if clicked.
cv.addEventListener(‘mousedown’, function(e) {
var x = e.pageX - rect.left, y = e.pageY-rect.top;
allTexts.forEach(function(txt) {
if (txt.Intersects(x,y)) txt.draw(’#F00’);
})
});