1

I want to draw a copy of this image on top of it but further down, but the .onclick isn't working for my image object. I tested it already and it works perfectly fine with canvas.onclick but not with my image 'sticky'.

code is below:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");

var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {

    context.drawImage(sticky, 0, 0);
};

sticky.onclick = function() {

    context.drawImage(sticky, 0, 100);
};

</script>
user3150635
  • 509
  • 2
  • 9
  • 26

1 Answers1

2

Your event needs to be on your canvas, not the image. Because when created, an image object isn't automatically added to the dom.

And when a canvas draw an image, it duplicates it, it copies pixels into itself.

So add your image to the dom, and listen for the click on your canvas.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");
var sticky = new Image();
var sticky2 = new Image();

sticky.src = "http://lorempixel.com/250/60/";
sticky2.src = "http://lorempixel.com/150/60/";

sticky.onload = function() {
  context.drawImage(sticky, 0, 0);
};

canvas.onclick = function() {
  context.drawImage(sticky2, 0, 100);
};
<canvas id="myCanvas"></canvas>
Yoann
  • 3,020
  • 1
  • 24
  • 34
  • where would I put body.appendChild(sticky);? wherever I put it it still doesn't work... – user3150635 Oct 06 '14 at 00:17
  • Thank you! the code works now, but there are two bugs. first, there's a second 'sticky' image below my canvas that only showed up when I added 'sticky' to the dom and I want to make it go away. second, when i keep clicking it, is it continually drawing images at (0,100)? if not, how do I get it to do that ad infinitum? – user3150635 Oct 06 '14 at 00:31
  • Define 'ad infinitum', do you mean (0, 100n)? – Yoann Oct 06 '14 at 01:34
  • And you don't need to add your image to the dom if you don't need it. You only need to listen to the click on your canvas. (Updated my answer) Also, the click `draw` on the previous `draw` each time. – Yoann Oct 06 '14 at 01:47