admin管理员组

文章数量:1424363

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.

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.

Share Improve this question asked Jul 12, 2012 at 13:25 Evgeni RoitburgEvgeni Roitburg 2,09723 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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./100/100);
}

Or set the CSS via JavaScript:

canvas.style.backgroundImage = 'url(http://placekitten./100/100)';

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]);

本文标签: javascriptload image to fabric canvas backgroundStack Overflow