我正在尝试将图像插入到 Canvas 元素中。以此代码为例(http://jsfiddle.net/n3L6e1wp/)。我想用 img 标签替换 Canvas 中显示的文本。 我试图通过以下方式替换 div 的内容:
<img src='<%= asset_path('layout/image.jpg') %>' id='picture' style='max-height:100%'>
但没有任何显示,我什至不确定我能做到这一点。
提前致谢!
最佳答案
canvas drawImage
方法将接受一个 html img 元素作为图像源,因此您可以直接这样做:
ctx.drawImage(document.getElementById('picture'),0,0);
示例代码和演示:
window.onload=function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
ctx.drawImage(document.getElementById('picture'),0,0);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>
<!-- src is for this demo. You can still use your <%...%> -->
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/sun.png' id='picture' style='max-height:100%'>
关于javascript - 将 img 标签插入 Canvas 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32454095/