这行得通
img.src = "assets/img.png";
img.addEventListener('load', function () {
textureContext.drawImage(this, 0, 0);
texture.update();
});
现在如何使用页面上已有的 Canvas 元素进入这段代码。像这样的事情。
var img = document.getElementById("canvas1");
textureContext.drawImage(img, 0, 0);
texture.update();
我正在寻找纯 JavaScript 解决方案。
最佳答案
您需要使用方法Canvas#toDataURL方法
The HTMLCanvasElement.toDataURL() method returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.
img.src = document.getElementById("canvas1").toDataURL();
工作示例:
const canvas = document.getElementById("canvas");
const img_from_canvas = document.getElementById("img_from_canvas");
const context = canvas.getContext("2d");
context.rect(10, 10, 150, 100);
context.fill();
img_from_canvas.src = canvas.toDataURL();
<p>canvas</p>
<canvas id="canvas"></canvas>
<p>image from canvas</p>
<img id="img_from_canvas"/>
关于javascript - 将 Canvas 元素分配给 img.src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093740/