简体   繁体   中英

Crop an image displayed in a Canvas

I have a canvas tag:

<canvas width="321" height="240" id="img_source"></canvas>

I want to add a crop functionality, so I made a resizeable div that can identify the borders of cropped image through dragging the corners of the div using the mouse. It looks like the image below:

在此处输入图片说明

在此处输入图片说明

I'm currently using "toDataURL()" to convert the data from the canvass to an image that can be displayed by an <img> tag. My question is, How will I convert to an image only part of the canvas that was identified by the resizeable div?

Use the method getImageData with the selected rectangle coordinates. For example:

let imageData = ctx.getImageData(65, 60, 100, 100);

Then create a secondary canvas with the desired sizes and use putImageData to set the pixels:

let canvas1 = document.createElement("canvas");
canvas1.width = 100;
canvas1.height = 100;
let ctx1 = canvas1.getContext("2d");
ctx1.rect(0, 0, 100, 100);
ctx1.fillStyle = 'white';
ctx1.fill();
ctx1.putImageData(imageData, 0, 0);

Finally use toDataURL to update the image:

dstImg.src = canvas1.toDataURL("image/png");

See the full sample I've prepared for you in CodePen

Create a new canvas at destination size, draw in the cropped image using drawImage() and insert that canvas into the DOM avoiding using img and data-uri:

var ccanvas = document.createElement("canvas"),
    cctx = ccanvas.getContext("2d");

ccanvas.width = w;
ccanvas.height = h;

// draw with crop arguments
cctx.drawImage(image_src,  x, y, w, h,  0, 0, w, h);
//                         ^^^^^^^^^^ source region
//                                      ^^^^^^^^^^ dest. region

// insert cropped image somewhere in the DOM tree:
document.body.appendChild(ccanvas);

 window.onload = function() { var img = document.getElementById("image_src"); document.body.appendChild(region2canvas(img, 150, 60, 220, 200)); } function region2canvas(img, x, y, w, h) { var ccanvas = document.createElement("canvas"), cctx = ccanvas.getContext("2d"); ccanvas.width = w; ccanvas.height = h; // draw with crop arguments cctx.drawImage(img, x, y, w, h, 0, 0, w, h); return ccanvas; }
 <img src="http://i.imgur.com/kWI4Cmz.png" id="image_src">

The key to cropping from one image is that the context's drawImage method allows us to render a cropped section of the source image to the canvas.

context.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh);

img - Source image object
sx - Source x
sy - Source y
sw - Source width
sh - Source height
dx - Destination x
dy - Destination y
dw - Destination width
dh - Destination height

创建一个新画布,并将所选部分复制到该新画布,然后从该新画布中获取 toDataURL()。

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