如何使用javascript

时间:2018-06-06 05:30:31

标签: javascript html html5-canvas

我对画布很新。我想要做的是我可以使用输入在画布上编写文本,并且可以通过拖动它的角来调整它的大小。此外,我应该能够在画布中拖动文本位置。 以下是我想要的屏幕截图! enter image description here

2 个答案:

答案 0 :(得分:1)

Canvas是栅格,而不是矢量。通过简单地绘制和调整文本大小,您可以预期它会变得模糊或像素化。每次用户移动光标时重新绘制整个画布,同时调整大小不会产生最佳性能。考虑使用svg代替。如果您确实需要画布并且不想自己实现所有功能,则可以使用paperjs库。

http://paperjs.org/reference/pointtext/

答案 1 :(得分:1)

如@ hirasawa-yui所述,您可以使用Paper.js极大地方便您在画布中实现所需的功能。

这是简化的sketch,显示了拖动/调整大小交互的可能实现。

// create item
var item = new PointText({
    content: 'Custom text content',
    point: view.center,
    justification: 'center',
    fontSize: 30,
    selected: true
});

// init variables so they can be shared by event handlers
var resizeVector;
var moving;

// on mouse down...
function onMouseDown(event) {
    // ...do a hit test on item bounds with a small tolerance for better UX
    var cornerHit = item.hitTest(event.point, {
        bounds: true,
        tolerance: 5
    });
    // if a hit is detected on one of the corners...
    if (cornerHit && ['top-left', 'top-right', 'bottom-left', 'bottom-right'].indexOf(cornerHit.name) >= 0) {
        // ...store current vector from item center to point
        resizeVector = event.point - item.bounds.center;
    // ...else if hit is detected inside item...
    } else if (item.hitTest(event.point, { fill: true })) {
        // ...store moving state
        moving = true;
    }
}

// on mouse drag...
function onMouseDrag(event) {
    // ...if a corner was previously hit...
    if (resizeVector) {
        // ...calculate new vector from item center to point
        var newVector = event.point - item.bounds.center;
        // scale item so current mouse position is corner position
        item.scale(newVector / resizeVector);
        // store vector for next event
        resizeVector = newVector;
    // ...if item fill was previously hit...
    } else {
        // ...move item
        item.position += event.delta;
    }
}

// on mouse up...
function onMouseUp(event) {
    // ... reset state
    resizeVector = null;
    moving = null;
}

// draw instructions
new PointText({
    content: 'Drag rectangle to move, drag corners to resize.',
    point: view.center + [0, -50],
    justification: 'center'
});