将图像加载到织物画布背景

时间:2012-07-12 13:25:27

标签: javascript canvas html5-canvas filereader fabricjs

嗨我试图上传图片并将其作为画布背景。代码段:

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]); 
}
问题是画布没有显示背景。我可以在chrome devtools中看到画布背景src。背景实际上已经设置但不知何故它没有显示。

2 个答案:

答案 0 :(得分:2)

这看起来很奇怪。如果你想在HTMLCanvasElement上有背景图片,为什么不通过CSS设置背景图片?

#myCanvas {
  background-image: url(http://placekitten.com/100/100);
}

或者通过JavaScript设置CSS:

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

答案 1 :(得分:1)

请尝试以下代码:

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