裁剪画布中显示的图像 [英] Crop an image displayed in a Canvas

查看:93
本文介绍了裁剪画布中显示的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个画布标签:

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

我想添加裁剪功能,因此我制作了一个可调整大小的div,可以通过使用鼠标拖动div的角来识别裁剪图像的边界.如下图所示:

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:

我当前正在使用"toDataURL()"将画布中的数据转换为可以由<img>标记显示的图像.我的问题是,如何将仅由可调整大小的div标识的画布的一部分转换为图像?

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?

推荐答案

对选定的矩形坐标使用方法getImageData.例如:

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

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

然后创建具有所需大小的辅助画布,并使用puImageData设置像素:

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

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

最后使用toDataURL更新图像:

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

CodePen 中查看我为您准备的完整示例.

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

这篇关于裁剪画布中显示的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆