简体   繁体   中英

Copy user selection from one canvas to another

I'm trying to implement a simple, select area on canvasA and then copy area to canvasB, I've got the selection part working but the drawing of the copied area doesn't want to work. The idea is that the user will select an area and then that selection will appear on another canvas when they finish the selection, ie say mousedown, drag rectangular area, mouseup (copy appears)

I confess I'm not much of a front end developer so fear I'm missing something obvious about how this stuff works as I'm just trying to knock something together to prove a concept and understand the basics at the moment.

JSFiddle is here - http://jsfiddle.net/bw4gw83a/2

HTML

<canvas id="original" width=300 height=300></canvas>
<canvas id="copybit" width=300 height=300></canvas>

Javascript

var original = document.getElementById("original");
var CTXoriginal = original.getContext("2d");
var copybit = document.getElementById("copybit");
var CTXcopybit = copybit.getContext("2d");


var background = new Image();
background.src = "https://i.imgur.com/F1pJYM1.jpg";

background.onload = function(){
    CTXoriginal.drawImage(background, 0, 0)
}

var imageData = CTXoriginal.getImageData(10, 10, 100, 100);
CTXcopybit.putImageData(imageData,0,0);

Any pointers appreciated.

Si

The following guide might be helpful.

http://www.i-programmer.info/programming/graphics-and-imaging/2078-canvas-bitmap-operations-bitblt-in-javascript.html

It mentions you can draw a section of the image using

drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh)

Where s is source, and d is destination.

From there you just have to determine the position of the click and drag to work out the co-ordinates and width/heights.

I've updated your fiddle just to demonstrate. It's very crude, so just click once somewhere in the top left of the image, then click again somewhere in the bottom right.

http://jsfiddle.net/treerock/1zpc8fz0/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM