在canvas内的当前鼠标位置添加一个Textarea

我想在canvas上添加一些文本信息。 当我在canvas上点击鼠标时,它应该在当前鼠标位置显示一个文本区域。 也应该可以选择,拖动和旋转textarea。如何使用HTML5 canvas和javascript实现此function?

下面的代码是由dreame4提供的,适合允许拖动( jsfiddle )。

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在canvas中创建文本,然后查看有关如何旋转它的文章。 您需要明确跟踪文本区域的位置和旋转角度。 canvas元素的事件监听器必须检查鼠标是否在文本中,在这种情况下它开始拖动或在外面,在这种情况下它创建/移动文本。

处理在canvas上单击并使用坐标显示textarea的代码示例:

HTML

  

JS:

 var canvas = document.getElementById("c"), textarea = null; canvas.addEventListener('click', function(e) { if(!textarea) { textarea = document.createElement('textarea'); textarea.className = 'info'; 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); 

其余function更复杂。 可能你想使用像jQuery UI这样的外部库。

编辑:在样式中缺少’px’。 谢谢斯图尔特。