简体   繁体   中英

Edit Zoomed Images displayed in HTML5 canvas element

I am using HTML5 canvas to display an image with zoomin/out feature. It works fine. However, i also need to edit the image. For instance on mouse click, I need to replace a certain size of grid in the image ( size is dynamic, not always fixed). So i am using context.putImageData(imgData, x, y) , where imgData is a grid of 10*10 ( for instance) to be replaced at x, y location.

This works fine. But when I zoomin/out, all my image edits disappear. I think the reason being , putImageData, replace only in memory image on the canvas element, and never updates original image source.

I am wondering how to overcome this issue ? I suppose I need to edit the orignal image and then draw it using drawImage() instead of using context.putImageData() directly.

But how do I do it ?

//@ startup //currentScale =1.0

var photo = new Image();
photo.src = "./Ship1.png";
photo.addEventListener('load', eventPhotoLoaded, false); 
function drawImage()
{

this.context.drawImage(photo, 0, 0, photo.width,photo.height, 0, 0, photo.width * currentScale,  photo.height* currentScale);
}

//It properly displays the image

// Onmouse click

theCanvas.addEventListener('click', function(evt) {
var rect = this.theCanvas.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;

//newGird is an array of cells containing R,G,B and Alpha values
context.putImageData(newGird, x, y)

//The above code correctly updates the canvas image at point x,y with the newGrid. Looks great so far.

//have button for zoomin/out. And on button click, I change the value of currentScale and call drawImage() method. Zoom in/out is done properly, but as expected the changes done by putImageData() are overwritten by original image, because those changes were never saved back to the image.

This problem is solved now. In step 3, scaling can done by changing canvas.style.width and canvas.style.height instead of calling drawImage again. So, It works fine. Thanks philipp and yoursweater

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