0

我想在画布上画一条线

context.globalCompositeOperation = 'destination-out';
context.globalAlpha = 0.118;

结果如下所示:

在此处输入图像描述

如果图像是黄色矩形,则为背景。我使用一个圆圈将其拖放到图像上,它将绘制线条。如您所见,我的画线不是那么平滑。您可以看到圆圈并且没有复合线。

我在这里创建了一个 JSFiddle

console.clear();

var history = new Array();

var imageObj = new Image();
var img = null;

stage = new Konva.Stage({
    container: 'container',
    width: 600,
    height: 400
});
layer = new Konva.Layer();
stage.add(layer);

var rect = new Konva.Rect({
      x: 30,
      y: 30,
      width: 438,
      height: 300,
      fill: 'yellow'
    });
layer.add(rect);

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');



var circle = new Konva.Circle({
    x: 0,
    y: 0,
    radius: 40,
    opacity: 0.7,
    fill: '#ff5e0a',
    stroke: '#d95009',
    strokeWidth: 1,
    draggable: true
});
layer.add(circle);


circle.on('dragmove touchmove', function (e) {
    erase(e.evt.clientX, e.evt.clientY, circle.radius(), img.x(), img.y());
});


imageObj.onload = function () {
    canvas.width = imageObj.width;
    canvas.height = imageObj.height;
    context.drawImage(imageObj, 0, 0, imageObj.width, imageObj.height);

    img = new Konva.Image({
        x: 30,
        y: 30,
        image: canvas
    });

    layer.add(img);

    circle.moveToTop();
    layer.draw();
};

imageObj.crossOrigin = "anonymous";
imageObj.src = "https://dl.dropboxusercontent.com/u/47067729/darth-vader.jpg";


function erase(absX, absY, radius, imgX, imgY) {
    var x = 0;
    var y = 0;

    // set pointer
    circle.x(absX);
    circle.y(absY);

    x= absX - imgX;
    y= absY - imgY;

    context.globalCompositeOperation = 'destination-out';
    context.globalAlpha = 0.118;
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI);
    context.fill();

    layer.draw();
}

如何在看不到每一小块圆圈的地方绘制更平滑和更复杂的线条?

4

1 回答 1

1

假设您的 Konva thingie 不提供现成的解决方案,您将不得不以恒定位移插入触摸屏事件位置。

像这样的东西:

circle.on('dragmove touchmove', function (e) {

    if (circle.prev_pos) {
        var dx = e.evt.clientX - circle.prev_pos.x;
        var dy = e.evt.clientY - circle.prev_pos.y;
        var dist = Math.max (Math.abs(dx), Math.abs(dy));
        dx = dx / dist;
        dy = dy / dist;
        var x = circle.prev_pos.x;
        var y = circle.prev_pos.y;
        var d;
        for (d = 0 ; d < dist ; d++)
        {
            erase(x, y, circle.radius(), img.x(), img.y());
            x += dx;
            y += dy;
        } 
    }
    circle.prev_pos = { x:e.evt.clientX, y:e.evt.clientY};
});

看到这个小提琴

于 2015-02-20T22:19:14.807 回答