我想在画布上添加一些文本信息。当我在画布上单击鼠标时,它应该在当前鼠标位置显示一个文本区域。还应该可以选择、拖动和旋转文本区域。如何使用 HTML5 canvas 和 javascript 实现此功能?
下面的代码是由dreame4提供的,适合允许拖动(jsfiddle http://jsfiddle.net/ABY63/1/).
var canvas = document.getElementById("c"),
textarea = null;
function mouseDownOnTextarea(e) {
var x = textarea.offsetLeft - e.clientX,
y = textarea.offsetTop - e.clientY;
function drag(e) {
textarea.style.left = e.clientX + x + 'px';
textarea.style.top = e.clientY + y + 'px';
}
function stopDrag() {
document.removeEventListener('mousemove', drag);
document.removeEventListener('mouseup', stopDrag);
}
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', stopDrag);
}
canvas.addEventListener('click', function(e) {
if (!textarea) {
textarea = document.createElement('textarea');
textarea.className = 'info';
textarea.addEventListener('mousedown', mouseDownOnTextarea);
document.body.appendChild(textarea);
}
var x = e.clientX - canvas.offsetLeft,
y = e.clientY - canvas.offsetTop;
textarea.value = "x: " + x + " y: " + y;
textarea.style.top = e.clientY + 'px';
textarea.style.left = e.clientX + 'px';
}, false);
然而,旋转需要一个完全不同且更复杂的解决方案 - 使用以下命令在画布内制作文本context.fillText
然后看到这个帖子 https://stackoverflow.com/questions/3167928/drawing-rotated-text-on-a-html5-canvas关于如何旋转它。您需要明确跟踪文本区域的位置和旋转角度。 canvas 元素的事件侦听器必须检查鼠标是否在文本内(在这种情况下它开始拖动)或在外部(在这种情况下它创建/移动文本)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)