1

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

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

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

4

2 回答 2

5

putImageData()将始终使用它自己的width以及我们可以在drawImage()height中拥有的destinationWidthdestinationHeight

它对上下文矩阵变换不敏感,因此缩放它不会对此方法产生影响。

它的一件事是dirtyWidthdirtyHeight参数,这对我们没有多大帮助,因为虽然它们可以减少将要绘制的表面积,但它们不会修改包含的像素,也不能无论如何都要让这个表面增长...... (您可以查看此 Q/A以更深入地了解它)


为了实现你想要的,你必须实际渲染你的 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>

于 2018-07-18T05:43:30.580 回答
1

scale() 方法缩放当前图形,更大或更小。

this.context.putImageData(imgData, firstPointX, firstPointY);
this.context.scale(1.5,1.5);
this.context.drawImage(this.canvas, 0, 0); // <-- added
于 2018-07-17T18:25:49.393 回答