2D Context具備了基本的文字繪製功能,不過想要做成在Canvas可以直接打字的效果,還是需要花一些功夫嘗試。
雖然2D Context具備了文字繪製功能,但是光靠他要做出在Canvas上直接輸入文字的效果還是有困難,不過問題其實不是出在Canvas上。如果要能直接輸入文字,DOM Keyboard Event就需要能支援用「輸入法」來輸入的功能。不過仔細看一下DOM3 Event的規格,實際上能取得的只有code跟char,前者代表所按下鍵的鍵盤代碼,後者代表所按下鍵的ASCII字元,這些跟用輸入法輸入的文字其實無關。目前在DOM3 Event的定義中,Composition事件比較像是這類的功能,不過只有Firefox真正可以支援,等於白搭。
取而代之的方法,還是使用一個text input來做輸入,不過這樣就會碰到討厭的「對齊」問題。如果什麼都沒有調整,很難把輸入框跟最後畫到Canvas上面的文字對齊,這樣就跟所視即所得差了一些
經過一些嘗試,靠著把輸入框的line-height與vertical-align做調整,加上一些偏移,總算是對齊了。X軸的偏移還算是比較固定,但是Y軸其實會跟著字型大小偏移的位置還會不一樣。目前稍微可以解決的方式,是把輸入框的line-height設為可輸入字型大小的最大值,另外把Canvas跟輸入框的垂直對齊都設定為middle,去除很難記算的對齊問題。(不論對齊top、bottom、baseline等,上下空間會跟字型大小有關係,而且不會是整數)
先來看一下繪製文字的程式:
var drawText = {
type: 'drawText',
run: function(text, x, y) {
this.ctx.textAlign = 'left';
this.ctx.fillText(text, x, y, this.ctx.measureText(text).width);
}
}
tool.regist(drawText);
其實只要一行程式就可以做出來。但是要做出介面以及輸入文字的部份,就需要花一些功夫。除了在滑鼠事件中把文字繪製先過濾掉不處理,只處理按下滑鼠的事件(在適當座標顯示輸入框)。然後在輸入框的keypress事件中,偵測enter鍵是否按下,來停止輸入。為了可以改變文字的屬性,先把PaintTools的getter/setter做一些調整,加入一些新東西
get fontFace() {
return this._fontFace;
},
set fontFace(val) {
this._fontFace = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontFace', val);
this.emit('font', this.ctx.font);
},
get fontSize() {
return this._fontSize;
},
set fontSize(val) {
this._fontSize = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontSize', val);
this.emit('font', this.ctx.font);
},
get fontWeight() {
return this._fontWeight;
},
set fontWeight(val) {
this._fontWeight = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontWeight', val);
this.emit('font', this.ctx.font);
},
get fontStyle() {
return this._fontStyle;
},
set fontStyle(val) {
this._fontStyle = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontStyle', val);
this.emit('font', this.ctx.font);
}
在改變字型屬性時,同時會觸發相關事件。利用這個方式,可以簡化一些處理過程。為了讓輸入框跟Canvas的字型屬性一致,就可以利用font事件,在字型屬性調整時,一併修改輸入框的字型屬性:
tool.on('fillStyle', function(val) {
$('#keyin').css('color', val);
});
tool.on('font', function(val) {
$('#keyin').css('font', val);
});
最後利用onmousedown跟onkeypress兩個事件來把輸入功能實作出來:
$('#keyin').bind('keypress', function(e) {
if(e.which=='13') {
tool.do($(this).val(), start[0], start[1]);
start = [];
drawing = false;
$(this).css('display', 'none');
$(this).val('');
}
});
//drawing dom event
canvas.bind('mousedown', function(e) {
e.preventDefault();
if(!drawing && tool.drawType==='drawText') {
e.stopPropagation();
var offset = $(e.currentTarget).offset();
tool.ctx.textBaseline = 'middle';
var t = $('#keyin');
t.css('left', e.pageX+1+'px');
t.css('top', e.pageY-t.outerHeight()/2+1+'px');
t.css('display', 'block');
t.focus();
drawing = true;
start = [e.pageX-offset.left, e.pageY-offset.top];
}
if(!drawing && tool.drawType!=='drawText') {
$(this).data('cursor', $(this).css('cursor'));
$(this).css('cursor', 'pointer');
drawing = true;
if(tool.drawType=='strokeRect' || tool.drawType=='fillRect' || tool.drawType=='strokeCircle' || tool.drawType=='fillCircle' || tool.drawType=='strokeEclipse' || tool.drawType=='fillEclipse') {
tool.pushCanvas();
}
var offset = $(e.currentTarget).offset()
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
tool.do(x,y,x,y);
queue.push([x,y]);
}
});
mousedown事件中,第一個if會針對繪製文字做處理。同樣還是取得事件發生的座標,然後在適當的位置出現輸入框,等到按下Enter後,繪製到Canvas上,然後輸入框消失。
完整的程式如下:
<meta charset='utf-8'>
<link rel="StyleSheet" type="text/css" href="reset.css">
<style>
canvas {
border: solid 1px gray;
}
.panel {
margin: 5px 5px 5px 5px;
padding: 5px 5px 5px 5px;
border: solid 2px #336699;
width: 778px;
}
.tools {
margin-right: 5px;
padding: 2px 2px 2px 2px;
border: solid 2px #6699CC;
width: 120px;
height: 474px;
float:left;
}
label {
font-size: 10px;
}
span {
font-size: 9px;
color: red;
font-weight: bold;
}
#keyin {
border: none;
display: none;
position: absolute;
vertical-align: middle;
padding: 0 0 0 0;
margin: 0 0 0 0;
line-height: 24px;
}
</style>
<link rel="stylesheet" href="js/colorPicker.css" type="text/css" />
<script src='http://code.jquery.com/jquery-1.8.2.js'></script>
<script src='js/jquery.colorPicker.js'></script>
<script>
function EventEmitter() {
var handlers = {};
this.on = function(name, fn) {
if(typeof handlers[name] == 'undefined') handlers[name] = [];
handlers[name].push(fn);
};
this.emit = function() {
var name = arguments[0];
var args = [];
for(var i=1; i<arguments.length; i++) {
args.push(arguments[i]);
}
if(typeof handlers[name] !== 'undefined') {
handlers[name].forEach(function(fn) {
fn.apply(this, args);
})
}
};
}
</script>
<script>
(function(window, undefined) {
var document = window.document;
var tools = {}, queue = [], clones = [];
var PaintToolsProto = {
_drawType: 'freestyle',
_fontFace: 'sans-serif',
_fontSize: '10px',
_fontWeight: '400',
_fontStyle: 'normal',
get fillStyle() {
return this.ctx.fillStyle;
},
set fillStyle(val) {
this.ctx.fillStyle = val;
this.emit('fillStyle', val);
},
get strokeStyle() {
return this.ctx.strokeStyle;
this.emit('fillStyle', val);
},
set strokeStyle(val) {
this.ctx.strokeStyle = val;
this.emit('fillStyle', val);
},
get lineWidth() {
return this.ctx.lineWidth;
},
set lineWidth(val) {
this.ctx.lineWidth = val;
this.emit('lineWidth', val);
},
get lineCap() {
return this.ctx.lineCap;
},
set lineCap(val) {
this.ctx.lineCap = val;
this.emit('lineCap', val);
},
get lineJoin() {
return this.ctx.lineJoin;
},
set lineJoin(val) {
this.ctx.lineJoin = val;
this.emit('lineJoin', val);
},
get drawType() {
return this._drawType;
},
set drawType(val) {
this._drawType = val;
this.emit('drawType', val);
},
get fontFace() {
return this._fontFace;
},
set fontFace(val) {
this._fontFace = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontFace', val);
this.emit('font', this.ctx.font);
},
get fontSize() {
return this._fontSize;
},
set fontSize(val) {
this._fontSize = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontSize', val);
this.emit('font', this.ctx.font);
},
get fontWeight() {
return this._fontWeight;
},
set fontWeight(val) {
this._fontWeight = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontWeight', val);
this.emit('font', this.ctx.font);
},
get fontStyle() {
return this._fontStyle;
},
set fontStyle(val) {
this._fontStyle = val;
this.ctx.font = this.fontStyle + ' ' + this.fontWeight + ' ' + this.fontSize + ' ' + this.fontFace;
this.emit('fontStyle', val);
this.emit('font', this.ctx.font);
}
};
window['$C'] = function(ctx) {
var ret = new PaintTools(ctx);
ret.regist(freestyle);
ret.regist(strokeRect);
ret.regist(fillRect);
return ret;
}
var PaintTools = function(_ctx) {
this.ctx = _ctx;
this.emitter = EventEmitter;
this.emitter();
delete this.emitter;
};
PaintTools.prototype = PaintToolsProto;
PaintTools.prototype.regist = function(tool) {
if(typeof tool.type !== 'undefined' && typeof tool.run !== 'undefined') {
tools[tool.type] = tool;
}
};
PaintTools.prototype.do = function() {
var args = [];
for(var i=0; i<arguments.length; i++) {
args.push(arguments[i]);
}
if(typeof tools[this.drawType] !== 'undefined') {
tools[this.drawType].run.apply(this, args);
}
};
PaintTools.prototype.pushCanvas = function() {
clones.push(this.ctx.getImageData(0, 0, this.ctx.canvas.width, this.ctx.canvas.height));
};
PaintTools.prototype.popCanvas = function() {
if(clones.length>0) {
this.ctx.putImageData(clones.pop(), 0, 0);
}
};
PaintTools.prototype.restoreCanvas = function() {
if(clones.length>0) {
this.ctx.putImageData(clones[0], 0, 0);
}
};
PaintTools.prototype.dropCanvas = function() {
if(clones.length>0) {
clones.pop();
}
}
var freestyle = {
type: 'freestyle',
run: function(x, y, x1, y1) {
this.ctx.beginPath();
this.ctx.moveTo(x,y);
this.ctx.lineTo(x1,y1);
this.ctx.closePath();
this.ctx.stroke();
}
}
var strokeRect = {
type: 'strokeRect',
run: function(x, y, x1, y1) {
this.ctx.beginPath();
this.ctx.rect(x, y, x1-x, y1-y);
this.ctx.closePath();
this.ctx.stroke();
}
}
var fillRect = {
type: 'fillRect',
run: function(x, y, x1, y1) {
this.ctx.beginPath();
this.ctx.rect(x, y, x1-x, y1-y);
this.ctx.closePath();
this.ctx.fill();
}
}
})(window);
</script>
<script>
$(document).ready(function() {
// global variables
var canvas = $('#canvas');
var context = canvas[0].getContext('2d');
var drawing = false;
var queue = [];
var start = [];
var tool = $C(context);
// drawing tool setup
tool.on('drawType', function(v) {$('#drawtypestatus').html(v);});
tool.lineCap = 'round';
tool.lineJoin = 'round';
tool.lineWidth = 1;
// color picker setup
$('#color1').colorPicker({
pickerDefault: 'ffffff',
onColorChange: function(id, val) {
tool.fillStyle = val;
}
});
$('#color2').colorPicker({
pickerDefault: 'ffffff',
onColorChange: function(id, val) {
tool.strokeStyle = val;
}
});
tool.on('fillStyle', function(val) {
$('#keyin').css('color', val);
});
tool.on('font', function(val) {
$('#keyin').css('font', val);
});
$('#keyin').bind('keypress', function(e) {
if(e.which=='13') {
tool.do($(this).val(), start[0], start[1]);
start = [];
drawing = false;
$(this).css('display', 'none');
$(this).val('');
}
});
//drawing dom event
canvas.bind('mousedown', function(e) {
e.preventDefault();
if(!drawing && tool.drawType==='drawText') {
e.stopPropagation();
var offset = $(e.currentTarget).offset();
tool.ctx.textBaseline = 'middle';
var t = $('#keyin');
t.css('left', e.pageX+1+'px');
t.css('top', e.pageY-t.outerHeight()/2+1+'px');
t.css('display', 'block');
t.focus();
drawing = true;
start = [e.pageX-offset.left, e.pageY-offset.top];
}
if(!drawing && tool.drawType!=='drawText') {
$(this).data('cursor', $(this).css('cursor'));
$(this).css('cursor', 'pointer');
drawing = true;
if(tool.drawType=='strokeRect' || tool.drawType=='fillRect' || tool.drawType=='strokeCircle' || tool.drawType=='fillCircle' || tool.drawType=='strokeEclipse' || tool.drawType=='fillEclipse') {
tool.pushCanvas();
}
var offset = $(e.currentTarget).offset()
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
tool.do(x,y,x,y);
queue.push([x,y]);
}
});
canvas.bind('mousemove', function(e) {
e.preventDefault();
if(drawing && tool.drawType!=='drawText') {
var old = queue.shift();
if(tool.drawType=='strokeRect' || tool.drawType=='fillRect' || tool.drawType =='strokeCircle' || tool.drawType=='fillCircle' || tool.drawType=='strokeEclipse' || tool.drawType=='fillEclipse') {
tool.restoreCanvas();
queue.push(old);
}
var offset = $(e.currentTarget).offset();
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
tool.do(old[0],old[1],x,y);
if(tool.drawType == 'freestyle') {
queue.push([x,y]);
}
}
});
canvas.bind('mouseup', function(e) {
if(drawing && tool.drawType==='drawText') drawing = false;
if(drawing && tool.drawType!=='drawText') {
$(this).css('cursor', $(this).data('cursor'));
tool.dropCanvas();
var old = queue.shift();
var offset = $(e.currentTarget).offset();
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
tool.do(old[0], old[1], x, y);
drawing = false;
}
});
canvas.bind('mouseleave', function(e) {
if(drawing && tool.drawType!=='drawText') {
$(this).css('cursor', $(this).data('cursor'));
tool.dropCanvas();
var old = queue.shift();
var offset = $(e.currentTarget).offset();
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
tool.do(old[0], old[1], x, y);
drawing = false;
}
});
// tool panel event
$('#linewidth').bind('change', function() {
tool.lineWidth = $(this).val();
});
$('#freestyle').bind('click', function() {
tool.drawType = 'freestyle';
});
$('#strokerect').bind('click', function() {
tool.drawType = 'strokeRect';
});
$('#fillrect').bind('click', function() {
tool.drawType = 'fillRect';
});
$('#strokecircle').bind('click', function() {
tool.drawType = 'strokeCircle';
});
$('#fillcircle').bind('click', function() {
tool.drawType = 'fillCircle';
});
$('#strokeeclipse').bind('click', function() {
tool.drawType = 'strokeEclipse';
});
$('#filleclipse').bind('click', function() {
tool.drawType = 'fillEclipse';
});
$('#drawtext').bind('click', function() {
tool.drawType = 'drawText';
});
$('#fontface').bind('change', function() {
tool.fontFace = $(this).val();
});
$('#fontsize').bind('change', function() {
tool.fontSize = $(this).val();
});
$('#fontweight').bind('change', function() {
tool.fontWeight = $(this).val();
});
$('#fontstyle').bind('change', function() {
tool.fontStyle = $(this).val();
});
// define new drawtype and method
var strokeCircle = {
type: 'strokeCircle',
run: function(x1, y1, x2, y2) {
var radius = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2), 2);
this.ctx.beginPath();
this.ctx.arc(x1, y1, radius, 0, 2*Math.PI, true);
this.ctx.closePath();
this.ctx.stroke();
}
};
tool.regist(strokeCircle);
var fillCircle = {
type: 'fillCircle',
run: function(x1, y1, x2, y2) {
var radius = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2), 2);
this.ctx.beginPath();
this.ctx.arc(x1, y1, radius, 0, 2*Math.PI, true);
this.ctx.closePath();
this.ctx.fill();
}
};
tool.regist(fillCircle);
var strokeEclipse = {
type: 'strokeEclipse',
run: function(x1, y1, x2, y2) {
this.ctx.beginPath();
var xc1 = x1, yc1 = y1 - Math.abs(y2-y1), xc2 = x2, yc2 = y1 - Math.abs(y2-y1), xx2 = x2, yy2 = y1,
xc3 = x2, yc3 = y1 + Math.abs(y2-y1), xc4 = x1, yc4 = y1 + Math.abs(y2-y1);
this.ctx.moveTo(x1, y1);
this.ctx.bezierCurveTo(xc1, yc1, xc2, yc2, xx2, yy2);
this.ctx.bezierCurveTo(xc3, yc3, xc4, yc4, x1, y1);
this.ctx.closePath();
this.ctx.stroke();
}
}
tool.regist(strokeEclipse);
var fillEclipse = {
type: 'fillEclipse',
run: function(x1, y1, x2, y2) {
this.ctx.beginPath();
var xc1 = x1, yc1 = y1 - Math.abs(y2-y1), xc2 = x2, yc2 = y1 - Math.abs(y2-y1), xx2 = x2, yy2 = y1,
xc3 = x2, yc3 = y1 + Math.abs(y2-y1), xc4 = x1, yc4 = y1 + Math.abs(y2-y1);
this.ctx.moveTo(x1, y1);
this.ctx.bezierCurveTo(xc1, yc1, xc2, yc2, xx2, yy2);
this.ctx.bezierCurveTo(xc3, yc3, xc4, yc4, x1, y1);
this.ctx.closePath();
this.ctx.fill();
}
}
tool.regist(fillEclipse);
var drawText = {
type: 'drawText',
run: function(text, x, y) {
this.ctx.textAlign = 'left';
this.ctx.fillText(text, x, y, this.ctx.measureText(text).width);
}
}
tool.regist(drawText);
});
</script>
<div class='panel'>
<div class='tools' id='tools'>
<div>
<label for='drawtypestatus'>Draw Type: </label><span id='drawtypestatus'></span><br>
<hr size='1' width='100%'>
</div>
<div>
<label for='color1'>Fill: </label><div style='display:inline-block'><input type='text' id='color1' name='color1' value='#000000'></div><br>
<label for='color2'>Stroke: </label><div style='display:inline-block'><input type='text' id='color2' name='color2' value='#000000'></div><br>
<label for='linewidth'>Line Width: </label><select id='linewidth'>
<option value="1">1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="7">7</option>
</select>
<hr size='1' width='100%'>
</div>
<div>
<button id="freestyle">freesytle</button>
<button id='strokerect'>Stroke Rectangle</button>
<button id='fillrect'>Fill Rectangle</button>
<button id='strokecircle'>Stroke Circle</button>
<button id='fillcircle'>Fill Circle</button>
<button id='strokeeclipse'>Stroke Eclipse</button>
<button id='filleclipse'>Fill Eclipse</button>
<button id='drawtext'>Draw Text</button>
<hr size='1' width='100%'>
</div>
<div>
<label for='fontface'>Font: </label><select id='fontface'>
<option value='sans-serif'>sans-serif</option>
<option value='serif'>serif</option>
<option value='cursive'>cursive</option>
<option value='fantasy'>fantasy</option>
<option value='monospace'>monospace</option>
</select>
<label>Size: </label><select id='fontsize'>
<option value='10px'>10px</option>
<option value='12px'>12px</option>
<option value='14px'>14px</option>
<option value='16px'>16px</option>
<option value='18px'>18px</option>
<option value='20px'>20px</option>
<option value='24px'>24px</option>
</select>
<label>Weight: </label><select id='fontweight'>
<option value='400'>default</option>
<option value='700'>bold</option>
</select>
<label>Style: </label><select id='fontstyle'>
<option value='normal'>normal</option>
<option value='italic'>italic</option>
</select>
</div>
</div>
<canvas id="canvas" width='640' height='480'></canvas>
</div>
<input type='text' id='keyin' size='20'>
首先來看看操作介面:
輸入文字看看:
阿咧,mac的抓圖軟體抓不到我的文字框跟游標,然後繪製到Canvas又長得一樣,好像沒辦法比較。不過經過一些測試,包含一些字型大小跟風格的組合,看起來還是會在繪製時跟文字輸入框的文字位置稍微差一點...這就先放過吧。
明天再嘗試一些架構上的改進跟小功能,再接下來就開始試試看怎麼跟WebSocket整合,做出多人共用白板的功能。