我已经能够调整画布的大小,并且还包括触摸事件。但是由于某些原因,我无法获得覆盖图像来填充画布。
我正在使用recommended code from fabric.js
canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
width: width,
height: height,
// Needed to position overlayImage at 0/0
originX: 'left',
originY: 'top'
});
我的Fiddle有相当多的代码,因为我不确定是大小调整器还是触摸事件可能导致此问题。
答案 0 :(得分:1)
摆弄琴弦的问题源于以下事实:在Fabric.js中,设置width
和height
不会将图像缩放到给定的值,而是设置{{1 }} 容器。您需要做的是在fabric.Image
的回调中调用canvas.overlayImage.scaleToWidth(width)
(或.scaleToHeight(height)
),以便图像实际缩放以覆盖整个画布:
setOverlayImage()
//Image Edit
var canvas = new fabric.Canvas('c', {
preserveObjectStacking: true
});
canvas.setWidth(window.innerWidth);
canvas.setHeight(window.innerWidth);
fabric.Image.fromURL("https://4.img-dpreview.com/files/p/E~TS590x0~articles/3925134721/0266554465.jpeg", function(img) {
img.scale(0.5).set({
left: 150,
top: 150,
angle: 0
});
canvas.add(img).setActiveObject(img);
});
var info = document.getElementById('info');
function resize() {
var canvasSizer = document.getElementById("imageEditor");
var canvasScaleFactor = canvasSizer.offsetWidth / 525;
var width = canvasSizer.offsetWidth;
var height = canvasSizer.offsetHeight;
var ratio = canvas.getWidth() / canvas.getHeight();
if ((width / height) > ratio) {
width = height * ratio;
} else {
height = width / ratio;
}
var scale = width / canvas.getWidth();
var zoom = canvas.getZoom();
zoom *= scale;
canvas.setDimensions({
width: width,
height: height
});
canvas.setViewportTransform([zoom, 0, 0, zoom, 0, 0])
canvas.setOverlayImage('https://i.imgur.com/1CURvP5.png', function() {
canvas.overlayImage && canvas.overlayImage.scaleToWidth(width)
canvas.renderAll()
}, {
// Needed to position overlayImage at 0/0
originX: 'left',
originY: 'top'
});
}
window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);
var textObj = new fabric.IText("Test Text", {
fontSize: 22,
top: 362.5,
left: 262.5,
hasControls: true,
fontWeight: 'bold',
fontFamily: 'Montserrat',
fontStyle: 'normal',
centeredrotation: true,
originX: 'center',
originY: 'center'
});
canvas.add(textObj);
canvas.renderAll();
canvas.on({
'touch:gesture': function() {
var text = document.createTextNode(' Gesture ');
info.insertBefore(text, info.firstChild);
},
'touch:drag': function() {
var text = document.createTextNode(' Dragging ');
info.insertBefore(text, info.firstChild);
},
'touch:orientation': function() {
var text = document.createTextNode(' Orientation ');
info.insertBefore(text, info.firstChild);
},
'touch:shake': function() {
var text = document.createTextNode(' Shaking ');
info.insertBefore(text, info.firstChild);
},
'touch:longpress': function() {
var text = document.createTextNode(' Longpress ');
info.insertBefore(text, info.firstChild);
}
});
(我必须在其他地方重新上传 jail_cell_bars.png 图片,因为原始主机无法配合使用)