admin管理员组文章数量:1416329
I'm trying to insert an image into a canvas element. Take this code for exemple (/). I want to replace the text displayed in the canvas by an img tag. I've tried to replace the content of the div by :
<img src='<%= asset_path('layout/image.jpg') %>' id='picture' style='max-height:100%'>
But nothing displays and I'm not even sure I can do this.
Thanks in advance !
I'm trying to insert an image into a canvas element. Take this code for exemple (http://jsfiddle/n3L6e1wp/). I want to replace the text displayed in the canvas by an img tag. I've tried to replace the content of the div by :
<img src='<%= asset_path('layout/image.jpg') %>' id='picture' style='max-height:100%'>
But nothing displays and I'm not even sure I can do this.
Thanks in advance !
Share Improve this question asked Sep 8, 2015 at 9:29 DannyDanny 31 silver badge2 bronze badges 1-
you cant put images inside a
<canvas>
... you can draw them onto a canvas – Alex Commented Sep 8, 2015 at 9:45
2 Answers
Reset to default 3The canvas drawImage
method will accept an html img element as an image source, so you can directly do this:
ctx.drawImage(document.getElementById('picture'),0,0);
Example code and a Demo:
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./u/139992952/multple/sun.png' id='picture' style='max-height:100%'>
Try this code, will work fine.
var canvas = document.getElementsByTagName('canvas'),
var content = canvas.getContext('2d');
function insertImage() {
image = new Image();
image.src = 'assets/img.png'; //any img src
image.onload = function(){
content.drawImage(image, 300, 300);
}
}
insertImage();
本文标签: javascriptInsert an img tag into Canvas elementStack Overflow
版权声明:本文标题:javascript - Insert an img tag into Canvas element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745248599a2649682.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论