AsianTemptation
AsianTemptation

Reputation: 123

Downscale canvas element then get imageData

I need users to be able to draw a canvas element that then needs to be converted into an array of length 784 so it be can be fed into an algorithm. The array should be of pixel shade intensity, which I can find by use the ctx.getImageData() method. However, since the user needs to draw it, the canvas element is 280x280 instead of the required 28x28 meaning I need to downscale the image drawn on the 280x280 canvas, then use getImageData.

I've tried just getting every 100th value from the 280x280 image data array, but I'm not sure if that would actually work, and I've struggled to draw the resulting array so I can't verify.

var guess = document.getElementById('guess');
var canvasBig = document.getElementById('canvasBig');
var ctxBig = canvasBig.getContext('2d');
var canvasSmall= document.getElementById('canvasSmall');
var ctxSmall = canvasBig.getContext('2d');

var canvas = new fabric.Canvas('canvasBig', {
   isDrawingMode: true,
});
canvas.freeDrawingBrush.width = 50;

guess.addEventListener('click', function() {
  var imageData = ctx.getImageData(0,0, canvasBig.width, canvasBig.height)
  var resized = []
  for(var i = 0; i < imageData.length; i++){
    if(i % 100 == 0){
      resized.push(imageData.length)
    }
  }
  console.log(imageData)
  ctxSmall.putImageData(imageData, 0, 0)
});

Upvotes: 0

Views: 131

Answers (1)

kshetline
kshetline

Reputation: 13682

You can simply draw the larger canvas itself (without having to use getImageData) onto the smaller canvas, scaling to down when you draw:

ctxSmall.drawImage(canvasBig, 0, 0, 280, 280, 0, 0, 28, 28);

Upvotes: 1

Related Questions