作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
为什么如果我尝试使用 .html() 在 dom 的多个区域中显示相同的 canvas 元素,只会输出最后一个。看一下下面的示例,我创建一个 canvas 元素并将其存储在一个变量中,以便使用 .html() 输出到两个 dom 元素,但第一个元素是空白的。为什么会发生这种情况?
jQuery(document).ready(function(){
var c = $('<canvas />');
c[0].height = 200;
c[0].width = 200;
var ctx = c[0].getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
$('.canvas_one').html(c);
$('.canvas_two').html(c);
});
.canvas_one{
background-color: blue;
min-height: 10px;
}
.canvas_two{
background-color: red;
min-height: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="canvas_one"></div>
<div class="canvas_two"></div>
最佳答案
问题是因为 c
只引用同一个、单个 canvas
实例。因此,当您将其包含在第二个 html()
调用中时,您实际上将其从原始位置移动到目标。
如果您想创建一个新的 canvas
实例,那么您可以使用 clone()
来创建它,如下所示:
$('.canvas_two').html(c.clone());
jQuery(document).ready(function() {
var c = $('<canvas />');
c[0].height = 200;
c[0].width = 200;
var ctx = c[0].getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
$('.canvas_one').html(c);
$('.canvas_two').html(c.clone());
});
.canvas_one {
background-color: blue;
min-height: 10px;
}
.canvas_two {
background-color: red;
min-height: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="canvas_one"></div>
<div class="canvas_two"></div>
关于jquery - 如何在 jQuery 中创建 Canvas 并在多个区域中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60075234/
我是一名优秀的程序员,十分优秀!