AbsoluteNoob
AbsoluteNoob

Reputation: 1

Place an image element on top of a canvas

I would like to place the picture of the hand on my black canvas next to the face. Is this possible to do? Is there a way to determine the position of the picture?

Here's my code:

<script type="text/javascript" src="hand.jpg"></script>

<img src="hand.jpg" id="y" />
<canvas id="myCanvas" width="1600" height="1200"></canvas>
<script>
  var canvas;
  var canvasContext;

  window.onload = function() {
    canvas = document.getElementById('myCanvas');
    canvasContext = canvas.getContext('2d');
    canvasContext.fillStyle = 'black';

    canvasContext.fillRect(0, 0, canvas.width, canvas.height);
    //Draws a circle
    canvasContext.beginPath();
    canvasContext.fillStyle = 'yellow';
    canvasContext.arc(800, 400, 400, 400, 2 * Math.PI, true);
    canvasContext.fill();
    //draws head
    canvasContext.beginPath();
    canvasContext.fillStyle = 'white';
    canvasContext.arc(600, 200, 100, 100, 2 * Math.PI, true);
    canvasContext.fill();
    //draws eye1
    canvasContext.beginPath();
    canvasContext.fillStyle = 'white';
    canvasContext.arc(1000, 200, 100, 100, 2 * Math.PI, true);
    canvasContext.fill();
    //draws eye2
    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(580, 175, 50, 50);
    //draws pupil1
    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(980, 175, 50, 50);
    //draws pupil2
    canvasContext.fillStyle = 'black';
    canvasContext.fillRect(650, 550, 300, 6.5);
    //draws mouth

    function changingImg() {
      document.getElementById("y").src = "hand.jpg"
    }
  }
</script>

Is there anyway to fix this?

Upvotes: 0

Views: 54

Answers (1)

Kenzoid
Kenzoid

Reputation: 294

I'm assuming <script type="text/javascript" src="hand.jpg"></script> was a small mistake as it should be <script type="text/javascript" src="someFile.js"></script>. But if you were to make a JS file and link to it like that you would probably want to remove the plain <script> tag below.

Moving on, if you wanted to change the size of the image you can simply change the .width and .height property of the element variable.

For example:

var image = document.getElementById('y');

image.width = 1920; // Sets image's width to 1920
image.height = 1080; // Set's image's height to 1080

If you wanted to read the width and height values you can do so like this:

var image = document.getElementById('y');
var imageWidth = image.width; // Image's width
var imageHeight = image.height; // Image's height

Upvotes: 1

Related Questions