繁体   English   中英

在画布上放置一个图像元素

[英]Place an image element on top of a canvas

我想把手的照片放在我的黑色画布上,靠近脸。 这是可能的吗? 有没有办法确定图片的位置?

这是我的代码:

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

有没有什么办法解决这一问题?

我假设<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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM