在画布中选择绘制的对象

时间:2018-01-04 11:37:11

标签: javascript html canvas

我在canvas中有一个带有context.drawImage()的绘制图像,我想选择那个图像来拖动它在同一个画布中移动(与MS Paint选择工具相同)。我怎样才能在javascript中编写代码?

function crop(xStart,yStart,xLast,yLast){
    canvas.width = xLast - xStart;
    canvas.height = yLast - yStart;
    context.clearRect(0, 0, canvas.width,canvas.height);           drawFromAux(xStart,yStart,xLast,yLast,0,0);
    return canvas.toDataURL();
}
// img is my original image
function select(xStart,yStart,xLast,yLast){

    selection.src = crop(xStart,yStart,xLast,yLast);
    selection.draggable = "true";
    
    context.clearRect(0, 0, canvas.width,canvas.height);                
    canvas.width = img.width;
    canvas.height = img.height;
    context.clearRect(0, 0, canvas.width,canvas.height);                
    context.drawImage(img, 0, 0);
    context.clearRect(xStart, yStart, xLast - xStart,yLast - yStart); 
    context.drawImage(selection,0,0); 

}

1 个答案:

答案 0 :(得分:1)

使用不应 Canvas.jsPointer.js

要做的事情:

  1. 创建包含x,y和原始图像的图像对象
  2. 将其渲染到画布
  3. 听取鼠标移动并检查是否按下了鼠标按钮
  4. 在画布上鼠标和图像之间进行简单的点碰撞检测,以便能够“选择它”并拖动它
  5. 正在加载Pointer.jsCanvas.js

    <script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script>
    <script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/Pointer.js"></script>
    

    1)创建图像对象并不是很难:

    const image = {
        image: new Image(),
        x: canvas.width / 2 - image.width / 2, // centered in canvas
        y: canvas.height / 2 - image.height / 2 // centered in canvas
    };
    
    image.image.src = ' <url> ';
    

    2)将该图像渲染到画布(使用Canvas.js

    const canvas = new Canvas('my-canvas', 500, 500).start();
    
    canvas.on('draw', function ( renderer ) {
        renderer.drawImage(image.image, image.x, image.y);
    });
    

    3)聆听鼠标移动和移动图像(使用Pointer.js

    const pointer = new Pointer( canvas.element );
    
    let moveImage = false;
    
    pointer.on('move', function ( event ) {
        if( moveImage ) {
            image.x += (event.x - pointer.getMoveHistory(-2).x);
            image.y += (event.y - pointer.getMoveHistory(-2).y);
        }
    });
    

    4)指针碰撞检测(使用Pointer.js

    pointer.on('down', function () {
    
        moveImage = pointer.touches({ x: image.x, y: image.y, width: image.image.width, height: image.image.height });
    
    });
    
    pointer.on('up', function () {
    
        moveImage = false;
    
    });
    

    JSFiddle:https://jsfiddle.net/GustavGenberg/3h39b9h1/

    希望这可以帮助你:)!