设置画布上图像的大小 [英] Set size of image from canvas

查看:163
本文介绍了设置画布上图像的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在项目中使用量角器,在测试中,我想将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 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();
  });
});

我无法更改画布的大小。在我的小提琴中,您可以看到DOM中的图像大小已更改,但是当我下载时,由于画布大小,图片仅200x200像素。我想念什么?

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?

推荐答案

问题是,调整图像元素的宽度和高度实际上并不会改变其原始大小。当在浏览器中显示时,它会显得更大,但是图像的原始大小仍然是画布的大小。

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>

这篇关于设置画布上图像的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆