问题
hi im trying to upload an image and put it as canvas background. code snippet:
function handleMenuImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.src = event.target.result;
canvas.setWidth(img.width);
canvas.setHeight(img.height);
canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas));
//set the page background
menuPages[currentPage].pageBackground.src = img.src;
canvas.backgroundImageStretch = false;
}
reader.readAsDataURL(e.target.files[0]);
}
the problem is that the canvas not showing the background. i can see the canvas background src in chrome devtools. the background is actually have been set but somehow its not displayed.
回答1:
That seems strangely confusing. If you want a background image on an HTMLCanvasElement, why not just set the background image via CSS?
#myCanvas {
background-image: url(http://placekitten.com/100/100);
}
Or set the CSS via JavaScript:
canvas.style.backgroundImage = 'url(http://placekitten.com/100/100)';
回答2:
Try the following code:
var raw_reader = new FileReader();
raw_reader.onload = function (event){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.src = event.target.result;
canvas.setWidth(img.width);
canvas.setHeight(img.height);
canvas.setBackgroundImage(img.src, canvas.renderAll.bind(canvas));
//set the page background
menuPages[currentPage].pageBackground.src = img.src;
canvas.backgroundImageStretch = false;
}
reader.readAsDataURL(e.target.files[0]);
}
raw_reader.readAsBinaryString(e.target.files[0]);
来源:https://stackoverflow.com/questions/11452831/load-image-to-fabric-canvas-background