克隆 HTML canvas 及其内容
Clone an HTML canvas and its content
我有一段 HTML 代码,其中 canvas 我想通过单击按钮进行复制。到目前为止,我已经尝试过这段代码,但我对缺少的内容一无所知。如果你能包含任何一段代码,那对我来说真的很有用,因为我是初学者
谢谢
<canvas id="myCanvas" width="800px" height="800px"></canvas>
<script>
var oldCnv = document.getElementById("myCanvas");
function cloneCanvas(oldCanvas) {
//create a new canvas
var newCanvas = document.createElement("canvas");
var context = newCanvas.getContext("2d");
//set dimensions
newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height;
//apply the old canvas to the new one
context.drawImage(oldCanvas, 0, 0);
//return the new canvas
return newCanvas;
//append the new canvas on the page
document.body.appendChild(newCanvas);
}
</script>
<button onclick="cloneCanvas(oldCnv)">add canvas</button>
您不能将 onclick 操作中的参数 oldCnv 传递给该函数。除此之外,在你 return newCanvas
之后 document.body.appendChild(newCanvas)
将不会被调用。
以下将起作用。
使用此代码:
<canvas id="myCanvas" width="800px" height="800px"></canvas>
<script>
var oldCanvas = document.getElementById("myCanvas");
function cloneCanvas() {
//create a new canvas
var newCanvas = document.createElement("canvas");
var context = newCanvas.getContext("2d");
//set dimensions
newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height;
//apply the old canvas to the new one
context.drawImage(oldCanvas, 0, 0);
//return the new canvas
//append the new canvas on the page
document.body.appendChild(newCanvas);
}
</script>
<button onclick="cloneCanvas()">add canvas</button>
我有一段 HTML 代码,其中 canvas 我想通过单击按钮进行复制。到目前为止,我已经尝试过这段代码,但我对缺少的内容一无所知。如果你能包含任何一段代码,那对我来说真的很有用,因为我是初学者 谢谢
<canvas id="myCanvas" width="800px" height="800px"></canvas>
<script>
var oldCnv = document.getElementById("myCanvas");
function cloneCanvas(oldCanvas) {
//create a new canvas
var newCanvas = document.createElement("canvas");
var context = newCanvas.getContext("2d");
//set dimensions
newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height;
//apply the old canvas to the new one
context.drawImage(oldCanvas, 0, 0);
//return the new canvas
return newCanvas;
//append the new canvas on the page
document.body.appendChild(newCanvas);
}
</script>
<button onclick="cloneCanvas(oldCnv)">add canvas</button>
您不能将 onclick 操作中的参数 oldCnv 传递给该函数。除此之外,在你 return newCanvas
之后 document.body.appendChild(newCanvas)
将不会被调用。
以下将起作用。 使用此代码:
<canvas id="myCanvas" width="800px" height="800px"></canvas>
<script>
var oldCanvas = document.getElementById("myCanvas");
function cloneCanvas() {
//create a new canvas
var newCanvas = document.createElement("canvas");
var context = newCanvas.getContext("2d");
//set dimensions
newCanvas.width = oldCanvas.width;
newCanvas.height = oldCanvas.height;
//apply the old canvas to the new one
context.drawImage(oldCanvas, 0, 0);
//return the new canvas
//append the new canvas on the page
document.body.appendChild(newCanvas);
}
</script>
<button onclick="cloneCanvas()">add canvas</button>