Skip to content Skip to sidebar Skip to footer

Set Size Of Image From Canvas

So I'm using Protractor in my project and in my test I want to convert the canvas element to an image with a specific size. I have the conversion down but can't seem to change the

Solution 1:

The problem is that adjusting the width and height of the image element doesn't actually change its original size. It will appear larger when displayed in the browser, but the original size of the image is still the size of the canvas.

I've modified your fiddle to show you how you can create a new image with a desired size by dynamically creating a new canvas with the specified width and height and drawing your original image on it.

var can = document.querySelector('#canvas1');
var ctx = can.getContext('2d');
ctx.fillRect(50, 50, 50, 50);

var img = newImage();
img.src = can.toDataURL();
var link = document.createElement('a');
var img2 = resizeImage(img, 500, 500);
link.href = img2.src;
link.download = 'study-chart.png';
link.click();


functionresizeImage(img, w, h) {
  var result = newImage();
  var canvas = document.createElement('canvas');
  canvas.width = w;
  canvas.height = h;
  canvas.getContext('2d').drawImage(img, 0, 0, w, h);
  result.src = canvas.toDataURL();
  return result;
}
canvas {
  border: 1px solid gray;
}
<canvasid="canvas1"width="200"height="200"></canvas>

Solution 2:

Solution 3:

@Kurumi, your codes can work somehow but better to add onload method

var img = newImage();
        img.src = c.toDataURL('image/jpeg');
        var img2 = '';
        img.onload = function () {
            img2 = resizeImage(img, oWidth, oHeight);
            var link = document.createElement('a');
            img2.onload = function () {
                link.href = img2.src;
                link.download = 'study-chart.jpeg';
                link.click();
            }
        }

Post a Comment for "Set Size Of Image From Canvas"