Validate a contained pixel rectangle before reading a canvas crop
A crop rectangle needs a stated coordinate space. If an application requires a rectangle fully inside the drawing buffer, check that requirement before calling getImageData(). The browser API can return transparent black for the part of a requested rectangle outside the canvas. A stricter application rule can reject that rectangle instead.
裁剪矩形需要明确的坐标空间。如果应用程序要求矩形必须完全位于绘图缓冲区内,请在调用 getImageData() 之前检查该要求。浏览器 API 可能会针对请求矩形中超出画布的部分返回透明黑色。更严格的应用程序规则可以选择拒绝该矩形。
This example accepts only positive, integer-sized rectangles with nonnegative integer origins. function containedPixelRect(rect, canvasWidth, canvasHeight) { if (rect === null || typeof rect !== ‘object’) { throw new TypeError(‘Expected a rectangle object’); } const { x, y, width, height } = rect; const values = [x, y, width, height, canvasWidth, canvasHeight]; if (!values.every(Number.isSafeInteger) || x < 0 || y < 0 || width <= 0 || height <= 0 || canvasWidth <= 0 || canvasHeight <= 0 || x > canvasWidth - width || y > canvasHeight - height) { throw new RangeError(‘Rectangle must fit inside the drawing buffer’); } return { x, y, width, height }; } const rect = containedPixelRect( { x: 10, y: 5, width: 20, height: 15 }, 100, 80 ); // In browser code, after obtaining a 2D context: // const pixels = ctx.getImageData(rect.x, rect.y, rect.width, rect.height);
此示例仅接受具有非负整数原点且尺寸为正整数的矩形。函数 containedPixelRect(rect, canvasWidth, canvasHeight) 会检查矩形对象是否有效,并确保其完全位于绘图缓冲区内,否则抛出 RangeError。在浏览器代码中获取 2D 上下文后,即可使用该矩形调用 ctx.getImageData()。
Use the canvas drawing-buffer dimensions for this check. A rectangle expressed in displayed CSS coordinates needs to be mapped into that coordinate space first. Perform that mapping before using this validator.
请使用画布绘图缓冲区的尺寸进行此项检查。以显示的 CSS 坐标表示的矩形需要先映射到该坐标空间。请在执行此验证器之前完成该映射。
Passing the numeric check also does not grant permission to read a canvas containing restricted cross-origin image content. Handle the actual read failure at the call site. Keep that failure distinct from a rejected rectangle so a report can say which condition stopped the operation.
通过数值检查并不代表获得了读取包含受限跨域图像内容的画布的权限。请在调用处处理实际的读取失败。将此类失败与被拒绝的矩形区分开来,以便报告能够说明是哪种条件导致操作停止。
I work on Morphio. For an image crop request associated with that project, I would state the coordinate space and the containment rule with the rectangle values. API reference: getImageData().
我从事 Morphio 的开发工作。对于与该项目相关的图像裁剪请求,我会连同矩形值一起说明坐标空间和包含规则。API 参考:getImageData()。