简体   繁体   中英

canvas.getImageData is returning empty array having a canvas filled with canvas.fillText

I have a canvas, which is filled with the fillText function of canvas.. now i want to get the image data of this 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);

The array "imageData" conains the height and the width and a array which contains the pixel data which i need. But unfortuantely with this code i get a array full of zeros. the console output is:

ImageData { width: 24, height: 16, data: Uint8ClampedArray[1536] }

when i click on the data array i see that this is only containing zero values..

'Uint8ClampedArray [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1526 more… ] '

I have similar code with an canvas which have an image drawed with canvas.drawImage() inside, and this is working (the data array contains rgb values of each pixel in the canvas...).

What i am doing wrong?

You would have to set textBaseline property to top for the context, as the texts are drawn with a baseline set to bottom by default, making the text not visible within the canvas area if its drawn at 0, 0 position.

You'd also need to set the canvas's width and height before drawing the text.


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM