在画布内的当前鼠标位置添加一个Textarea [英] Add a Textarea inside the canvas at the current mouse position

查看:325
本文介绍了在画布内的当前鼠标位置添加一个Textarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add some textual information on the canvas. When i click mouse on a point of the canvas it should shown a text area at the current mouse position. It should be also possible to select,drag and rotate the textarea.How can achieve this functionality using HTML5 canvas and javascript?

推荐答案

下面,通过dreame4提供的代码适于允许拖动(的jsfiddle )。

The code below is that provided by dreame4 adapted to allow dragging (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元素的事件监听器必须检查鼠标是否在文本中,在这种情况下它开始拖动或在外面,在这种情况下它会创建/移动文本。

However, rotation requires quite a different and more complicated solution - make the text within the canvas using context.fillText and then see this post on how to rotate it. You'll need to explicitly keep track of the position and angle of rotation of the text area. The event listener for the canvas element will have to check whether the mouse is within the text, in which case it starts dragging, or outside, in which case it creates/moves the text.

这篇关于在画布内的当前鼠标位置添加一个Textarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆