我正在尝试通过按 1 个按钮来显示多个 Canvas 图像。我可以让一张图像完美运行,但第二张我不能。 我知道 ID 必须是唯一的,并且目前只有第一个 Canvas 会有图像。
HTML
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<div class="bg">
<img src="Assets/Images/background.png" alt="background">
</div>
<section class="content">
<img id="taxi" src="Assets/Images/PV.png" width="106" height="53">
<canvas id="myCanvas" width="106" height="53"
style="border:1px solid #d3d3d3; position:absolute; left:510px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas id="myCanvas" width="106" height="53"
style="border:1px solid #d3d3d3; position:absolute; left:310px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
</section>
</body>
</html>
JS
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,0,0,106,53);
}
我知道我可以通过更改 HTML 中的 id="myCanvas"
并重复脚本中的当前行来让它工作。但是最后的网页会有很多 Canvas ,我不想一直重复 javascript 代码。
是否有一种简单的方法可以实现我想要实现的目标?
最佳答案
HTML 元素不能有相同的 id。您需要以其他方式检索您的元素。有很多方法; getElementsByTagName
, getElementsByClassName
, querySelectorAll
, ...等
使用 querySelectorAll(".content > canvas");
这将选择所有直接子元素,它们是类为“content”的元素中的 Canvas 元素(在这种情况下是您的部分元素)。
function myCanvas() {
document.querySelectorAll(".content > canvas").forEach(c=>{
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,0,0,106,53);
});
}
基本示例:
function myCanvas() {
document.querySelectorAll(".content > canvas").forEach(c=>{
var ctx = c.getContext("2d");
var img = document.getElementById("taxi");
ctx.drawImage(img,0,0,106,53);
});
}
<section class="content">
<img id="taxi" src="https://static-s.aa-cdn.net/img/ios/899287106/45820b5b6bba46c7fcd853a46d554a34?v=1" width="106" height="53">
<canvas width="106" height="53" style="border:1px solid #d3d3d3; position:absolute; left:510px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas width="106" height="53" style="border:1px solid #d3d3d3; position:absolute; left:310px;top:117px;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
</section>
关于javascript - 使用 1 个按钮获取 2 个 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646353/