0

This code will copy a canvas to an image, until I try drawImage, which doesn't work. Run the code as is, click the 'send Canvas to Image', and the canvas image is placed in the img element. Uncomment the 'ctx.drawImage(img, 10, 10, 100, 100);' which should just add evee to the img element also, but instead, the canvas2image() function doesn't work at all. Any thoughts?

function draw2canvas() {
  var canvas = document.getElementById("thecanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
  ctx.fillRect(25, 25, 100, 100);
  ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
  ctx.fillRect(58, 74, 125, 100);

  var img = document.getElementById("test_image");
  //ctx.drawImage(img, 10, 10, 100, 100);

  ctx.font = "18px courier";
  ctx.fillStyle = "red";
  ctx.fillText("this is text", 20, 70);
}

function canvas2image() {
  var canvas = document.getElementById("thecanvas");
  document.getElementById("theimage").src = canvas.toDataURL();
}
<body onload="draw2canvas()">
  <img id="test_image" src="http://cdn.bulbagarden.net/upload/thumb/e/e2/133Eevee.png/250px-133Eevee.png" alt="test image" width="100" height="100">
  <br><br>

  <image id="theimage"></image>
  <canvas width=200 height=200 id="thecanvas"></canvas>
  <div>
    <button onclick="canvas2image()">send Canvas to Image</button>
  </div>
</body>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Next time, consider opening your browser's dev-tools console, from there you would have spotted what the issue was, and would probably have been able to find how to circumvent it by yourself. – Kaiido Sep 24 '18 at 02:16

1 Answers1

0

Well, I can spot straight away the problem with the HTML - there's no <image> element. Did you mean to make this <img>? It seems to work in the snippet I made, here's the output after clicking the button:

enter image description here

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • While `` indeed is not part of the html dtd, it will be generated as an HTMLUnknownElement and will have no incidence over drawImage nor on the code until there. – Kaiido Sep 24 '18 at 02:09