简体   繁体   中英

In-place crop of a <canvas> portion in HTML5

I've a <canvas> with an image already loaded and all the graphics coordinates needed for a crop (x, y, w, h) in an array.

What I'm trying to do is to crop the canvas directly , without a temporary other canvas to copy to/from (as suggested in other SO answers).

My idea is to:

1) Draw the selected area on the top-left corner of the canvas

2) Shrink the canvas size to the area

 $('#edit').on("click", function() { var img = $('#canvas'); var c = img[0]; var ctx = c.getContext("2d"); //var imageData = ctx.getImageData(0, 0, 100, 100); ctx.drawImage(c, 0, 0, 100, 100, 0, 0, 100, 100); c.width = 100; c.height = 100; }); var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(0, 0, 350, 350); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas id="canvas" width="350" height="350"></canvas> <input id="edit" type="button" value="Edit" /> 

Seems easy to me, but I'm missing something: when I execute, I get nothing https://jsfiddle.net/qg0znpu7/

What's wrong with my code? how can I fix it to obtain an in-place canvas crop?

Changing the width or height of a canvas will clear it. For that reason you will have to copy the data first.

You can use putImageData() for that:

 $('#edit').on("click", function() { var c = $('#canvas')[0]; var ctx = c.getContext("2d"); var imageData = ctx.getImageData(0, 0, 100, 100); c.width = 100; c.height = 100; ctx.putImageData(imageData, 0, 0); }); var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = "green"; ctx.fillRect(0, 0, 350, 350); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas id="canvas" width="350" height="350"></canvas> <input id="edit" type="button" value="Edit" /> 

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