我有一个 Canvas ,用canvas的fillText函数填充 Canvas .. 现在我想获取这个 Canvas 的图像数据。
var texttodraw = "hello world";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = '16px serif';
ctx.fillStyle = "#00ff00";
ctx.fillText(txttodraw, 0, 0);
console.log('the text is: ' + txttodraw);
canvas.width = ctx.measureText(txttodraw).width;
canvas.height = 16;
console.log('the image size is: ' + canvas.width + ' x ' + canvas.height);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
console.log(imageData);
数组“imageData”包含高度和宽度以及包含我需要的像素数据的数组。 但不幸的是,通过这段代码,我得到了一个充满零的数组。控制台输出为:
ImageData { 宽度:24,高度:16,数据:Uint8ClampedArray[1536] }
当我单击数据数组时,我发现它只包含零值..
'Uint8ClampedArray [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1526 更多...] '
我有一个类似的 Canvas 代码,里面有一个用 canvas.drawImage()
绘制的图像,并且这是有效的(数据数组包含 Canvas 中每个像素的 rgb 值... )。
我做错了什么?
最佳答案
您必须设置 textBaseline
属性设置为上下文的 top
,因为默认情况下,文本是使用设置为底部的基线绘制的,如果在 0 处绘制,则使得文本在 Canvas 区域内不可见, 0
位置。
在绘制文本之前,您还需要设置 Canvas 的宽度
和高度
。
var texttodraw = "hello world";
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = '20px Verdana';
canvas.width = ctx.measureText(texttodraw).width;
canvas.height = 20;
ctx.font = '20px Verdana';
ctx.textBaseline="top";
ctx.fillText(texttodraw, 0, 0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// check if image data array contains values other than 0
var data = imageData.data.filter(function(e) {
return e !== 0;
});
console.log(data);
关于javascript - canvas.getImageData 返回空数组,其中 Canvas 填充有 canvas.fillText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43899625/