gpt4 book ai didi

javascript - 将图像元素放置在 Canvas 顶部

转载 作者:行者123 更新时间:2023-12-02 22:15:19 31 4
gpt4 key购买 nike

我想将手的图片放在靠近脸部的黑色 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

关于javascript - 将图像元素放置在 Canvas 顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59402592/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com