仅将 Canvas 的一部分转移到新的 Canvas
Transfer only a Part of Canvas to a New Canvas
我有一个 canvas
,id
为 cnv
。
<canvas id='cnv'></canvas>
深色矩形是整个canvas。我想创建另一个 canvas,它只包含旧 canvas 中的白色区域。我如何将 canvas 的一部分转移到新的 canvas?
var cnv = document.getElementById('cnv');
我不知道上面的代码接下来要做什么。
假设您在 x、y、宽度和高度中指定了区域,您可以这样做:
function regionToCanvas(canvas, x, y, w, h) {
var c = document.createElement("canvas"), // create new canvas
ctx = c.getContext("2d"); // context for new canvas
c.width = w; // set size = w/h
c.height = h;
ctx.drawImage(canvas, x, y, w, h, 0, 0, w, h); // draw in region at (0,0)
return c; // return canvas
}
然后调用,例子:
var newCanvas = regionToCanvas(cnv, x, y, width, height);
document.body.appendChild(newCanvas); // add to DOM
我有一个 canvas
,id
为 cnv
。
<canvas id='cnv'></canvas>
深色矩形是整个canvas。我想创建另一个 canvas,它只包含旧 canvas 中的白色区域。我如何将 canvas 的一部分转移到新的 canvas?
var cnv = document.getElementById('cnv');
我不知道上面的代码接下来要做什么。
假设您在 x、y、宽度和高度中指定了区域,您可以这样做:
function regionToCanvas(canvas, x, y, w, h) {
var c = document.createElement("canvas"), // create new canvas
ctx = c.getContext("2d"); // context for new canvas
c.width = w; // set size = w/h
c.height = h;
ctx.drawImage(canvas, x, y, w, h, 0, 0, w, h); // draw in region at (0,0)
return c; // return canvas
}
然后调用,例子:
var newCanvas = regionToCanvas(cnv, x, y, width, height);
document.body.appendChild(newCanvas); // add to DOM