1
我有一个使用jquery在div元素内部定位canvas元素的问题。jquery canvas div offset
$("body").append($("<div></div>").attr("id", "divy"));
$("#divy").css({
"position":'absolute',
"cursor":'move',
"border":'1px solid red',
"left":'200px',
"top":'300px',
"outerHeight":'0px',
"innerHeight":'0px',
"margin":'0px',
"padding":'0px',
"min-height":'0px',
"height":'20px',
})
.html("<canvas id=civy width=20 height=20 ></canvas>")
liney=document.getElementById("civy");
oba=liney.getContext("2d");
oba.fillStyle='yellow';
oba.fillRect(0,0,50,50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您将看到黄色矩形掩映说得最多的div元素的红色轮廓的顶部。问题是,当我将canvas元素的高度设置为低于14时,黄色矩形不再与div的顶部对齐,并且间隙很明显。如预期,宽度将保持对齐到div的左侧。
.html("<canvas id=civy width=5 height=5 ></canvas>")
$("body").append($("<div></div>").attr("id", "divy"));
$("#divy").css({
"position":'absolute',
"cursor":'move',
"border":'1px solid red',
"left":'200px',
"top":'300px',
"outerHeight":'0px',
"innerHeight":'0px',
"margin":'0px',
"padding":'0px',
"min-height":'0px',
"height":'20px',
})
.html("<canvas id=civy width=5 height=5 ></canvas>")
liney=document.getElementById("civy");
oba=liney.getContext("2d");
oba.fillStyle='yellow';
oba.fillRect(0,0,50,50);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这发生在Chrome和探险家。 这是jquery/canvas/css的异常吗?
谢谢,格雷格
您正在将div的“height”设置为20px,并且您需要将其“line-height”设置为“0”。https://jsfiddle.net/dutagwd3/ – Kaiido
好的,谢谢但是我仍然得到了2 - 3像素当我将高度设置为1或2像素时出现间隙。 – Greg
你说得对,你需要将画布“display”设置为“block”https://jsfiddle.net/dutagwd3/2/ – Kaiido