问题
In my fabricjs I am making a canvas and adding an image to it and setting the image as background. and then I am clipping the cavas to some width and height.
After I clip the canvas I want a new canvas or same canvas with clipped area as background all covering the canvas with its width and height or can make new canvas with clipped area's height and width
Currently I am doing this..
function crop(url, name, left, top, width, height, callback) {
var c = document.createElement('canvas')
var id = "canvas_" + name
c.id = id
var canvas = new fabric.Canvas(id)
fabric.Image.fromURL(url, function(oImg) {
oImg.set({
selectable:false,
})
canvas.setDimensions({width:oImg.width, height:oImg.height})
canvas.add(oImg)
canvas.clipTo = function (ctx) {
ctx.rect(left, top, width, height)
console.log(ctx)
};
canvas.centerObject(oImg)
canvas.renderAll()
var img = canvas.toDataURL('image/png')
console.log(img)
callback(img)
}, {crossOrigin: "Anonymous"})
}
Here I can easyly clip the canvas with my given left, top, width and height but I am getting the same canvas with clipped clipped part and removed part with another color. But after clipping I want the clipped part to paint over canvas or set clipped part as background.
How can I do that ??
回答1:
Actually you cropped the rendering of the canvas.
To save the cropped area you must use Canvas.toDataURL() method, as you can see there is parameters top, left, width, height just use the same as you put into ctx.rect(left, top, width, height) and it will returns you a string representing the cropped area (base64 encoded).
Then use this string as your canvas new background image with Canvas.setBackgrounsImage
Your code should look like:
function crop(url, name, left, top, width, height, callback) {
var c = document.createElement('canvas')
var id = "canvas_" + name
c.id = id
var canvas = new fabric.Canvas(id)
fabric.Image.fromURL(url, function(oImg) {
oImg.set({
selectable:false,
})
canvas.setDimensions({width:oImg.width, height:oImg.height})
canvas.add(oImg)
canvas.centerObject(oImg)
canvas.renderAll()
var img = canvas.toDataURL({
format: 'image/png',
left: left,
right: right,
width: width,
height: height
})
console.log(img)
canvas.setBackgroundImage(img)
callback(img)
}, {crossOrigin: "Anonymous"})
}
来源:https://stackoverflow.com/questions/40083942/fabricjs-set-clipped-object-as-background-to-canvas-after-clipping