0

I am making the simple canvas application.

I want to use image for background of canvas.

I have found out that I should use drawImage(img,x,y).

This is my codes ,but drummap.img doesn't appear.

Where is wrong?

Test
<canvas id="leap-overlay"></canvas>
<script src="leap.js"></script>

<script>
var canvas = document.getElementById("leap-overlay");

// fullscreen
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;

// create a rendering context
var ctx = canvas.getContext("2d");
ctx.translate(canvas.width/2,canvas.height);


var img = new Image();
img.src = "drummap.jpg";
ctx.drawImage(img,0,0,100,100);
whitebear
  • 11,200
  • 24
  • 114
  • 237

2 Answers2

2

Assuming that your image drummap.jpg is located in said directory, create the image, set the onload to use the new image, and then set the src (see):

var img = new Image();
img.onload = function () {
    ctx.drawImage(img, 0, 0, 100, 100);
};

img.src = 'drummap.jpg';
Community
  • 1
  • 1
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • Thanks @Campari,but it doesn't work.. and no error message on console. 'drummap.jpg' is located in the correct directory. – whitebear Aug 03 '13 at 20:40
  • @whitebear What if you comment out your `ctx.fillStyle = "rgba(0,0,0,0.7)"` line. It might be drawing all black _on top_ of the image so you don't see it. – federico-t Aug 03 '13 at 20:42
  • I quoted this from sample codes ,now I delete ctx.fillStyle sentence,but it doesn't change. – whitebear Aug 03 '13 at 20:49
  • @whitebear That's strange because there's no error in your code as far I can tell. The only thing I can think of is that perhaps `drawImage` only takes 3 parameters. I've updated my answer now, see if it works. – federico-t Aug 03 '13 at 21:35
  • @whitebear the problem with your code is that you translate everything and hide it. You are using `canvas.height` and maybe you want to centralize it with `height/2`. Remember that at the beginning you set the height to the size of the document. – wendelbsilva Aug 03 '13 at 22:34
  • @wendelbsilva I agree with this. Maybe the problem all along was that you _were_ drawing the image but where it can't be seen. Just comment out the `ctx.translate(canvas.width/2,canvas.height);` line. – federico-t Aug 03 '13 at 22:39
  • You guys are spot on. That canvas.height is causing him to draw outside the viewable area. – ericjbasti Aug 04 '13 at 03:01
  • I agree the translate is messing it all up. – 0e4ef622 Apr 29 '14 at 05:23
2

I'm not sure how you're clearing your canvas or what your drawing, but remember your canvas is inherently transparent so feel free to give the canvas a css style background:

<canvas style = "background-image: url(pathtoyourimage.jpg);"></canvas>

Hope that helps.

ericjbasti
  • 2,085
  • 17
  • 19