gpt4 book ai didi

javascript - 使用 javascript 在图像上绘图

转载 作者:行者123 更新时间:2023-11-28 15:19:34 26 4
gpt4 key购买 nike

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

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()的日志时code> 它包含相同的图像。

我做错了什么吗?

最佳答案

当你设置 Canvas 的宽度或高度时,即使值相同,也会清空整个 Canvas ,你需要在绘制之前移动它们。 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);

还有其他因素会使您的文本不可见,例如放置文本的位置的颜色、基线,这些可能会使文本被写入但不可见。

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>

关于javascript - 使用 javascript 在图像上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32093573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com