剪辑图像以适应画布
画布将为您剪辑图像。
默认情况下,所有渲染都有一个设置为画布大小的剪辑区域。因为无论内容的大小如何都会执行剪辑(所有内容都必须根据剪辑区域进行检查,并且在硬件 (GPU) 中完成),所以渲染完整图像比渲染图像的一部分要快一些。
ctx.drawImage(image,x,y); // is the quicker function
ctx.drawImage(image,ix,iy,iw,ih,x,y,w,h); // the slower function
注意;当呈现的可见目标内容明显小于图像源时,这是不正确的
因此,要将裁剪后的图像渲染到较小的画布上,您只需找到中心,然后将图像渲染到距该中心一半大小的位置。
ctx.drawImage(
image, // image to render
(ctx.canvas.width - image.width) / 2, // center sub half image width
(ctx.canvas.height - image.height) / 2 // center sub half image height
);
如果您需要先放大,以下将渲染任何尺寸的图像以适应 1080 高度。
const imgW = 1920;
const imgH = 1080;
ctx.drawImage(
image, // image to render
(ctx.canvas.width - imgW) / 2, // center sub half image display width
(ctx.canvas.height - imgH) / 2, // center sub half image display height
imgW, imgH
);
裁剪图像
如果您希望节省内存并裁剪图像,请使用画布来保存裁剪后的图像。
function cropImageCenter(image,w,h){
const c = document.createElement("canvas");
c.width = w;
c.height = h;
const ctx = c.getContext("2d");
ctx.drawImage(image,(w - image.width) / 2, (h - image.height) / 2);
return c;
}
var img = new Image;
img.src = "imageURL1280by720.jpg";
img.onload = () => {
img = cropImageCenter(img, 600, 1080);
ctx.drawImage(img,0,0); /// render cropped image on to canvas
};
或放大和裁剪
function scaleCropToHeight(image,w,h){
const c = document.createElement("canvas");
c.width = w;
c.height = h;
const scale = h / image.height;
const ctx = c.getContext("2d");
ctx.drawImage(
image,
(w - image.width * scale) / 2,
(h - image.height * scale) / 2,
image.width * scale,
image.height * scale
);
return c;
}
var img = new Image;
img.src = "imageURL1920by1080.jpg";
img.onload = () => {
img = scaleCropToHeight(img, 600, 1080);
ctx.drawImage(img,0,0); /// render cropped image on to canvas
};