调整Fabricjs的背景图像大小
Resize background image of Fabricjs
我使用fabricjs来处理画布,并通过javascript将图像加载到其中。
我有一个函数可以调整画布的大小以使其响应,因此我想调整加载的背景图像的大小以适应画布,但保持纵横比。
我目前还没有找到符合我标准的例子,希望有人能提供帮助。
Javascript
var canvas = new fabric.Canvas('drawing_layer');
var img = new Image();
img.onload = function () {
canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas), {
originX: 'left',
originY: 'top',
left: 0,
top: 0
});
// initially sets width of canvas to fit the image
canvas.setDimensions({
width: img.width,
height: img.height
});
};
// below is a call to function that resizes the canvas
resizeCanvas();
//sets listener to resize event
window.addEventListener('resize', resizeCanvas);
您的resizeCanvas()应该看起来像:
resizeCanvas(width, height) {
canvas.backgroundImage.scaleToWidth(width);
canvas.backgroundImage.scaleToHeight(height);
canvas.setDimensions({width: width, height: height});
canvas.renderAll();
}
你应该没事。
为了通过保留图像的纵横比来设置背景图像,并将其设置在画布的中心。
const setBackgroundFromDataUrl = (dataUrl, options = {}) => {
if (!dataUrl) { return true; }
let img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = () => {
// maxWidth // Max width of the canvas
// maxHeight //Max height of canvas
let imgWidth = img.width; // Current image width
let imgHeight = img.height; // Current image height
let widthAspectRatio = maxWidth / imgWidth;
let heightAspectRatio = maxHeight / imgHeight;
let finalAspectRatio = Math.min(widthAspectRatio, heightAspectRatio)
let finalHeight = imgHeight * finalAspectRatio;
let finalWidth = imgWidth * finalAspectRatio;
let imgTop = 0;
if (maxHeight > finalHeight) {
imgTop = (Math.round(maxHeight) - Math.round(finalHeight)) / 2;
}
let imgLeft = 0;
if (maxWidth > finalWidth) {
imgLeft = (Math.round(maxWidth) - Math.round(finalWidth)) / 2;
}
let nsgImage = new fabric.Image(img).scale(finalAspectRatio);
nsgImage.set({ left: imgLeft, top: imgTop });
canvas.setBackgroundImage(nsgImage, () => canvas.renderAll());
}
img.src = dataUrl;
};
我在Angular 2+中的解决方案。
@HostListener('window:resize', ['$event'])
resizeCanvas(event?: any) {
const width: number = (window.innerWidth > 0) ? window.innerWidth : screen.width;
const height: number = (window.innerHeight > 0) ? window.innerHeight : screen.height;
const widthn: number = width * 0.7;
const heightn: number = height - 100;
canvas.setDimensions({
width: widthn,
height: heightn,
});
}
相关文章:
- 在视频和图像背景之间切换
- 带有图像背景的简单倒数计时器
- 无法设置图像背景图像
- 使用jQuery的透明图像背景
- 加快图像背景的页面加载速度
- HTML5 画布 - 如何在图像背景上画一条线
- IE8(Javascript和CSS)中带有拉伸BG的渐变图像背景
- 需要有关所选图像背景颜色的帮助.并将背景去除到所选择的其他图像
- 透明图像背景html5画布
- 你能帮我最大化我的图像背景吗
- 实现基于浏览器宽度的大图像背景拉伸的最简单方法
- Javascript改变图像/背景图像不工作
- 使悬停时的图像背景变暗,不影响文字
- 如何在javascript中扩展画布图像's背景并转换为文件对象
- JQuery移动设置图像背景与CSS
- 向图像(背景图像)添加超链接
- 课程互动360视频/图像背景在html5引导
- 在jQM中,为页面设置全屏CSS图像背景的正确/正确/实际方法是什么?
- 链接上随机图像背景
- 在JavaScript上设置图像背景形状