将图像元素放在画布上

时间:2019-12-19 02:36:25

标签: javascript image

我想将手的图片放在脸旁边的黑色画布上。这可能吗?有没有办法确定图片的位置?

这是我的代码:

<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>

反正有解决此问题的方法吗?

1 个答案:

答案 0 :(得分:1)

我假设<script type="text/javascript" src="hand.jpg"></script>是一个小错误,应该是<script type="text/javascript" src="someFile.js"></script>。但是,如果要像这样制作JS文件并链接到它,则可能要删除下面的普通<script>标签。

继续,如果您想更改图像的大小,只需更改元素变量的.width.height属性即可。

例如:

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

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

如果您想读取宽度和高度值,可以这样:

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