用javascript绘制图像

时间:2015-08-19 10:57:42

标签: javascript canvas html5-canvas

我试图在正在加载的图片上添加时间戳。所以我现在有以下代码来执行此操作:

var reader = new FileReader();

reader.onload = function (e) {
  var canvas = document.createElement("canvas");
  var context = canvas.getContext("2d");
  var imageObj = new Image();
  imageObj.src  = e.target.result;
  imageObj.onload = function(){
    canvas.width = this.width;
    canvas.height = this.height;

    context.drawImage(imageObj, 0,0);
    context.font = "40pt Calibri";
    context.fillText("My TEXT!", 20, 20);

    console.log(e.target.result);
    console.log(canvas.toDataURL("image/jpeg"));
    category.Pictures.push({offlineFoto: canvas.toDataURL("image/jpeg"), FileNameOnDevice: guid});
  };

    leftToProcess--;
    if (leftToProcess == 0) {
        $scope.loadingCat = false;
        $scope.loadingSubCat = false;
    }
    $scope.$apply();
};
reader.readAsDataURL(file);

当我检查e.target.result的console.log时,我得到了正确图像的base64,但当我检查canvas.toDataURL()的日志时,它包含相同的图像。

我做错了吗?

1 个答案:

答案 0 :(得分:4)

当您设置画布的宽度或高度时,即使值相同,它也会清空整个画布,您需要在绘制之前移动它们。 Spec:canvas-set-bitmap-dimensions

var reader = new FileReader();

reader.onload = function (e) {
  var canvas = document.createElement("canvas");
  var context = canvas.getContext("2d");
  var imageObj = new Image();
  imageObj.src  = e.target.result;
  imageObj.onload = function(){
    //
    canvas.width = this.width;
    canvas.height = this.height;
    // Move them before drawing anything.
    context.drawImage(imageObj, 0,0);
    context.font = "40pt Calibri";
    context.fillText("My TEXT!", 20, 20);
    console.log(e.target.result);
    console.log(canvas.toDataURL("image/jpeg"));
    category.Pictures.push({offlineFoto: canvas.toDataURL("image/jpeg"), FileNameOnDevice: guid});
  };

    leftToProcess--;
    if (leftToProcess == 0) {
        $scope.loadingCat = false;
        $scope.loadingSubCat = false;
    }
    $scope.$apply();
};
reader.readAsDataURL(file);

还有一些会使你的文字不可见,你放置文字的位置颜色baseline,这些可能会使文字写成但不可见。

var cv = document.getElementById('cv');
var ctx = cv.getContext('2d');

// Canvas cleared
cv.width = 300;
cv.height = 100;

ctx.fillRect(0, 0, 150, 100); // Fill half with black


ctx.font = "40pt Calibri";
ctx.fillText('1', 20, 20); // black alphabetic, so can't be seen

ctx.fillStyle = "red";
ctx.fillText("2", 135, 20); // red alphabetic. So some part is clipped.

ctx.textBaseline = "top";
ctx.fillText('3', 135, 20); // red top. All in region.
<canvas id="cv"></canvas>