我正在尝试将图像裁剪为画布中选定的红色矩形,但我被卡住了。你有什么主意吗?
我有关于坐标矩形和顶点的数据,我可以将其计算为像素。
let arr = [
[2333748.391245694, 6846480.395930305],
[2343351.375319867, 6838186.909684428],
[2339754.200562619, 6834021.75996551],
[2330151.216488446, 6842315.246211386],
[2333748.391245694, 6846480.395930305]
]
let xmax = 2343351.375319867
let xmin = 2330151.216488446
let ymax = 6846480.395930305
let ymin = 6834021.75996551
const mapWidth = xmax - xmin
const mapHeight = ymax - ymin
let h = 600;
let w = 637.0370370370371;
let A = [((arr[0][0] - xmin) * w) / mapWidth, 0]
let B = [w, ((ymax - arr[1][1]) * w) / mapHeight]
let C = [((xmax - arr[0][0]) * w) / mapWidth, h]
let D = [0, ((arr[1][1] - ymin) * w) / mapHeight]
var canvas = document.getElementById('image');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = () => {
context.drawImage(imageObj, ...A, ...B, ...C, ...D);
context.beginPath();
context.lineWidth = "6";
context.strokeStyle = "blue";
context.rect(...A, 5, 5);
context.rect(...B, 5, 5);
context.rect(...C, 5, 5);
context.rect(...D, 5, 5);
context.stroke();
};
imageObj.src = './test.png';
您有几个选择:
旋转基本图像,使剪辑矩形水平和垂直对齐。然后使用ctx.rect
定义剪辑区域。
根据@peter-b 的回答使用 CSS 剪辑
剪裁为多边形路径
第三个选项可能最简单,但这可能取决于您打算对裁剪后的图像做什么。即你打算旋转它吗?
这是使用您的图像和类似代码的工作片段:
const originalImg = new Image()
originalImg.onload = () => {
const srcCanvas = document.getElementById('srcCanvas')
const srcCtx = srcCanvas.getContext('2d')
// Calculate rect coordinates.
// These are hardcoded approximations for this snippet:
let srcA = [172, 0]
let srcB = [originalImg.width, originalImg.height / 4 * 3 - 50]
let srcC = [465, originalImg.height]
let srcD = [0, originalImg.height / 3]
srcCtx.moveTo(...srcA)
srcCtx.beginPath()
srcCtx.lineTo(...srcB)
srcCtx.lineTo(...srcC)
srcCtx.lineTo(...srcD)
srcCtx.lineTo(...srcA)
srcCtx.closePath()
srcCtx.clip()
srcCtx.drawImage(originalImg, 0, 0)
};
originalImg.src = 'https://i.stack.imgur.com/15BPX.png'
<div style="margin-bottom:5rem">
<h4>Clipped</h4>
<canvas id="srcCanvas" width="637" height="600" />
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句