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
Add a ment  | 

2 Answers 2

Reset to default 3

The 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