我有一个大的 Canvas 元素,我想将其克隆并显示在一个新的较小的 Canvas 元素中,以在网页加载后用作微型显示。
我提前创建了新的较小的空白 Canvas 元素,并将其附加到具有特定高度/宽度的 DOM。
想法是在页面加载后将大 Canvas 元素克隆到小 Canvas 元素中,使用:
//grab the context from your destination canvas
const destCtx = destinationCanvas.getContext('2d');
//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);
但是,所有显示的都是纯黑色背景。我的期望是较小的 Canvas 现在应该显示较大 Canvas 的重复设计,只是在较小的区域中。
我环顾四周,但到目前为止还没有找到解决问题的有效方法。
还尝试了以下方法:
const smallCanvas = document.getElementById('smallCanvas');
const bigCanvas = document.getElementById('bigCanvas');
smallCanvas.getContext('2d').drawImage(bigCanvas, 0, 0, bigCanvas.width, bigCanvas.height, 0, 0, smallCanvas.width, smallCanvas.height);
结果总是这样:
最佳答案
发生这种情况是因为除了源和位置之外,您没有将任何参数传递给 drawImage() 方法。在这种情况下,它将以 1:1 的比例将图像绘制到较小的 Canvas 上 - 这意味着您只能看到源 Canvas 的一小部分,不超过小 Canvas 的尺寸。
要解决此问题,您需要指定两个矩形(x、y、宽度、高度)- 第一个是较大的值,第二个是较小的值。
例如drawImage(source,sourceX,sourceY,sourceWidth,sourceHeight,targetX,targetY,targetWidth,targetHeight);
这是一个例子:
var bigCanvas = document.getElementById("bigCanvas");
var smallCanvas = document.getElementById("smallCanvas");
var img = new Image();
img.onload = function() {
bigCanvas.getContext('2d').drawImage(this, 0, 0);
smallCanvas.getContext('2d').drawImage(bigCanvas, 0, 0, bigCanvas.width, bigCanvas.height, 0, 0, smallCanvas.width, smallCanvas.height);
}
img.src = "https://picsum.photos/id/16/400/300";
<canvas id="bigCanvas" width="400" height="300"></canvas>
<canvas id="smallCanvas" width="40" height="30"></canvas>
关于javascript - 为什么我克隆的 HTML5 canvas 元素的内容显示为纯黑色背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56452413/