Set size of image from canvas

2019-08-13 18:36发布

问题:

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 size of the image. Here's my code:

it('should save an image', function(done) {
  //because of Protractor
  browser.driver.executeScript(function () {
    var can = document.querySelector('#workspace-canvas');
    var data = can.toDataURL("image/png");

    var image = new Image();
    image.width = 500;
    image.height = 500;
    image.src = data;
    console.log(image.height, image.width); //1122 1888
    var link = document.createElement('a');
    link.href = image.src;
    link.download = 'study-chart.png';
    link.click();

    return data;
  }).then(function (result) {
    browser.sleep(2000);
    done();
  });
});

I'm not able to change the size of the canvas. In my fiddle you can see the image size is changed in the DOM, but when I download it, the image is only 200x200 pixels because of the canvas size. What am I missing?

回答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 = new Image();
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();


function resizeImage(img, w, h) {
  var result = new Image();
  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;
}
<canvas id="canvas1" width="200" height="200"></canvas>



回答2:

Have you tried using the canvas context and scaling that and then saving out as an image?

context.scale



回答3:

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

        var img = new Image();
        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();
            }
        }