使用ctx.putImageData更改图像大小

时间:2018-07-17 18:20:30

标签: angular html5 typescript html5-canvas putimagedata

我正在做有角度的项目,必须将图像放在画布上。图片不是本地存储的,我只有图片数据,所以我用它。

this.context.putImageData(imgData, firstPointX, firstPointY);

现在我的问题是,我收到的图片是640 *480。我想知道是否有一种方法可以更改图像大小,以便我可以显示大于640 * 480的图片?

2 个答案:

答案 0 :(得分:1)

putImageData()将始终对 destinationWidth destinationHeight 使用其自己的widthheight drawImage()中。

对上下文矩阵转换不敏感,因此对其进行缩放不会对该方法产生影响。

它有一件事是 dirtyWidth dirtyHeight 自变量,虽然它们可以减少将要绘制的表面积,但对我们没有多大帮助,它们将不会修改所包含的像素,也无法使该表面增长... (您可以看到this Q/A以获得更深入的了解)< / sup>


要实现所需的功能,必须实际渲染ImageData,然后 drawImage 渲染的图像。

最全面的方法可能是使用第二个画布:

var ctx = canvas.getContext('2d'),
  cW = canvas.width,
  cH = canvas.height,
  imgW = 20,
  imgH = 20;

// generate a 20*20 ImageData full of noise
var data = new Uint8Array(imgW * imgH * 4);
crypto.getRandomValues(data);
var img = new ImageData(new Uint8ClampedArray(data.buffer), imgW, imgH);


// generate a second canvas
var renderer = document.createElement('canvas');
renderer.width = img.width;
renderer.height = img.height;
// render our ImageData on this canvas
renderer.getContext('2d').putImageData(img, 0, 0);
// Now we can scale our image, by drawing our second canvas
ctx.drawImage(renderer, 0,0, cW, cH);
<canvas id="canvas" height="100" width="100"></canvas>

在现代浏览器中,借助ImageBitmap对象,可以用一种更简洁的方式处理整个事情:

var ctx = canvas.getContext('2d'),
  cW = canvas.width,
  cH = canvas.height,
  imgW = 20,
  imgH = 20;

// generate a 20*20 ImageData full of noise
var data = new Uint8Array(imgW * imgH * 4);
crypto.getRandomValues(data);
var img = new ImageData(new Uint8ClampedArray(data.buffer), imgW, imgH);

createImageBitmap(img).then(renderer => 
  ctx.drawImage(renderer, 0,0, cW, cH)
)
<canvas id="canvas" height="100" width="100"></canvas>

第三种方法是,仅用于放大ImageData并避免使用第二个画布并在所有实现中可用,第三种方法是使用与ImageBitmap渲染器相同的画布,然后使用合成将该画布绘制到自身上: >

var ctx = canvas.getContext('2d'),
  cW = canvas.width,
  cH = canvas.height,
  imgW = 20,
  imgH = 20;

// generate a 20*20 ImageData full of noise
var data = new Uint8Array(imgW * imgH * 4);
crypto.getRandomValues(data);
var img = new ImageData(new Uint8ClampedArray(data.buffer), imgW, imgH);

// we use the main canvas as renderer
ctx.putImageData(img, 0, 0);
// Now we have an unscaled version of our ImageData
// let's make the compositing mode to 'copy' so that our next drawing op erases whatever was there previously
// just like putImageData would have done
ctx.globalCompositeOperation = 'copy';
// now we can draw ourself over ourself.
ctx.drawImage(canvas,
  0,0, img.width, img.height, // grab the ImageData part
  0,0, canvas.width, canvas.height // scale it
);
<canvas id="canvas" height="100" width="100"></canvas>

答案 1 :(得分:0)

scale()方法按比例放大或缩小当前图形。

this.context.putImageData(imgData, firstPointX, firstPointY);
this.context.scale(1.5,1.5);
this.context.drawImage(this.canvas, 0, 0); // <-- added