我使用画布上的getImageData并使用putImageData将其显示在另一个画布上。但这并不能覆盖整个画布,它会以原始尺寸显示图片。是否有一种方法可以使裁剪后的图片覆盖整个画布。谢谢您。这两个画布的尺寸均为300 x 300。
var c = document.getElementById("area_c");
var c2 = document.getElementById("area_c2");
var ctx = c.getContext("2d");
var ctx2 = c2.getContext("2d");
var imgData = ctx.getImageData(tx,new_ty ,x, new_y);
ctx2.putImageData(imgData, 0, 0);
答案 0 :(得分:1)
在此代码段中,您将看到如何使用css缩放另一个画布(我使用字符串而不是图像来避免CORS)
如果您想使用最近邻或像素化,我还添加了一个类
var c = document.getElementById("area_c");
var c2 = document.getElementById("area_c2");
var ctx = c.getContext("2d");
var ctx2 = c2.getContext("2d");
var w = 150;
var h = 70;
c.width = w;
c.height = h;
ctx.font = "50px Arial";
ctx.fillText('Image',0,50);
var x = 5;
var y = 15;
var cw = 60;
var ch = 35;
c2.width = cw;
c2.height = ch;
var scale = 2;
c2.style.width = scale*cw+'px';
c2.style.height = scale*ch+'px';
var imgData = ctx.getImageData(x,y,cw,ch);
ctx2.putImageData(imgData, 0, 0);
document.querySelector('input[name=pixelate]').addEventListener('change',()=>{c2.classList.toggle('pixelate')});
canvas {
border: 1px solid #333;
}
.pixelate {
image-rendering: auto;
image-rendering: crisp-edges;
image-rendering: pixelated;
}
<canvas id="area_c"></canvas>
<canvas id="area_c2"></canvas>
<input name="pixelate" type="checkbox"><label for="pixelate">Pixelate</label>