问题
What I'd like to achieve: I need to load different images in different canvas, move and resize them and show a preview. I'm using fabricJs. With rectangular canvas everything works fine, the problem is when I want to concatenate canvas with a diagonal section. Something like this:
I tried something with the transform property in CSS, but then I could no longer interract with the canvas. Any idea on how to do this? Or is there a way to have only one canvas with something like sections?
What I have right now (only part of the code to interract with the canvas, the preview it's another canvas where I draw again everything):
$( document ).ready(function() {
addImage('canvas1', 'imageLoader1');
addImage('canvas2', 'imageLoader2');
});
function addImage(canvas, input) {
var canvas = new fabric.Canvas(canvas);
document.getElementById(input).addEventListener('change', function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({
left: 0,
top: 0,
angle: 00,
width: 100,
height: 100
}).scale(0.9);
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png',
quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
}
.container {
width: 544px;
}
.canvas-container {
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.12/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
<canvas id="canvas1" width="272px" height="465px"></canvas>
<canvas id="canvas2" width="272px" height="465px" style="float: left;"></canvas>
</div>
<div>
<input type="file" id="imageLoader1" name="imageLoader1"/>
<input type="file" id="imageLoader2" name="imageLoader1"/>
</div>
</body>
回答1:
In reply to @Observer comment:
clipTo
is deprecated since v2.0.0. You could achieve this with clipPath (which is more powerful and more flexible than clipTo
since it accepts a fabric.Object
):
const canvas = new fabric.Canvas("canvas", {backgroundColor: "#d3d3d3"})
const container = new fabric.Rect({
width: 200,
height: 200,
left: 100,
top: 100,
})
const obj = new fabric.Circle({
radius: 50,
left: 150,
top: 150,
fill: "blue"
})
canvas.clipPath = container
canvas.add(obj)
canvas.requestRenderAll()
#canvas {
background: #e8e8e8;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.0.0-beta.5/fabric.min.js"></script>
<canvas id="canvas" width="400" height="400"></canvas>
来源:https://stackoverflow.com/questions/44529826/change-canvas-shape