0

I load a picture and draw it on canvas. With the mouse I can draw on the picture. Now I want to copy a defined part of an another picture to the same part of the shown picture. I thought I can copy the pixels from img2 to img1. Another idea is to place the pictures on top of the other (img1 oder img2) and cut an area from img1.

I don't know what is a possible way.

My try:

function loadPic() {
var ctx2 = document.getElementById('can').getContext('2d');  
img = new Image();
img2 = new Image();

img.onload = function() {
    ctx2.drawImage(img,0,0); 
}

img.src = 'Haut vorne m.bmp';
img2.src = 'Muskeln vorne m.bmp';

}

And the copy:

var g = img2.getImageData(262, 157, 200, 200);
ctx.putImageData(g, 55, 170); 

I get an error: img2.getImageData is not a function

Can anybody help ?

Thank you !

1
  • I think you need to apply the getImageData() call to a canvas, instead of to the image itself.
    – Peter B
    Apr 10, 2020 at 21:21

1 Answer 1

0

getImageData() is a function of canvas, not of Image. See here.

Replace img2.getImageData(...) with ctx.getImageData(...) or ctx2 if that's what you have.

1
  • But I have only one image on canvas. I need to copy from an image to canvas. I tryed var g = ctx.getImageData(262, 157, 200, 200); ctx.putImageData(g, 55, 170); I get an error: Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data. Or can I make a second canvas with is invisible and copy from there to the original canvas ? Apr 10, 2020 at 21:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.