canvas和img在chrome中工作但不是firefox

时间:2013-10-18 04:36:11

标签: javascript canvas cross-browser

我已经搜索了一些关于这个问题的结果,但它们都不适合我,所以我在这里发帖以获得一些帮助。基本上我的问题是当我点击生成按钮时,我希望画布中的图像显示在img元素中。但是,图像将显示在chrome但不是firefox!以下是我的编码......

<body onload="onLoad();">
  <canvas id="aimage">Your browser does not support the canvas tag.</canvas>
  <input type="button" value="Generate" onclick="genImage();" />
  <img id="cImg" name="cImg" src="${param.src}" />
 ...
</body>

和javascript ...

var tcanvas;
var scanvas;
var tcontext;
var imageURL;

function onLoad() {
    tcanvas = document.getElementById("aimage");
    tcontext = tcanvas.getContext("2d");
    scanvas = document.getElementById("cImg");
    imageURL = "${param.src}";
    update();                
}

function update() {
    var image = new Image();
    image.onload = function () {
        if (image.width != tcanvas.width)
            tcanvas.width = image.width;
        if (image.height != tcanvas.height)
            tcanvas.height = image.height;
        tcontext.clearRect(0, 0, tcanvas.width, tcanvas.height);
        tcontext.drawImage(image, 0, 0, tcanvas.width, tcanvas.height);
    }
    image.crossOrigin = 'anon';
    image.src = imageURL;
}

function genImage() {
    var url = tcanvas.toDataURL("image/jpeg");
    scanvas.crossOrigin = 'anon';
    scanvas.src = url;

    if(scanvas.width > 1000){
      scanvas.width = 1000;
    }
    if(scanvas.height > 1000){
      scanvas.height = 1000;
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

var scanvas, tcontext, tcanvas;
function genImage() {
    var url = tcanvas.toDataURL("image/jpeg");
    scanvas.src = url;
    if (scanvas.width > 1000) {
        scanvas.width = 1000;
    }
    if (scanvas.height > 1000) {
        scanvas.height = 1000;
    }
}
window.onload = function () {
    tcanvas = document.getElementById("aimage");
    tcontext = tcanvas.getContext("2d");
    scanvas = document.getElementById('cImg');
    var img = new Image();
    img.onload = function () {
        tcontext.drawImage(img, 0, 0, img.width, img.height)
    };
    img.src = "yourImage.jpg";
}