gpt4 book ai didi

jquery - HTML5 Canvas 对象

转载 作者:行者123 更新时间:2023-12-01 08:06:40 25 4
gpt4 key购买 nike

我在 html 页面中有一个 canvas html 元素:

<canvas id="myCanvas2" width="290" height="250" style="background-color:red"></canvas>

我想使用 jquery 访问 Canvas 。如果我尝试使用 jQuery 进行访问,它不起作用,如果我尝试使用 document.getElementById 则只有它起作用。

这是代码:

 var canvas = $("#myCanvas2");
console.log("Canvas : " + canvas + ", typeof : " + typeof(canvas));
canvas = document.getElementById('myCanvas2');
console.log("Canvas 2 : " + canvas + ", typeof : " + typeof(canvas));

不应该 $("#myCanvas2");和 document.getElementById('myCanvas2');一样吗??

我在控制台中收到以下内容:

  Canvas : [object Object], typeof : object
Canvas 2 : [object HTMLCanvasElement], typeof : object

canvas html元素可以使用jquery访问吗?

谢谢。

最佳答案

jQuery 总是将他的方法包装在 DOM 节点周围。这不仅仅是 Canvas 的情况。

如果你想通过 jQuery 访问 DOM 节点 Canvas,你必须使用 .get() method :

$("canvas").get(0).getContext("2d");
// or short hand
$("canvas")[0].getContext("2d");

请注意,您必须传递 index 才能获取 DOM 节点。否则你将拥有一个 DOM 节点数组。

关于jquery - HTML5 Canvas 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16180953/

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