Javascript 返回大数字的mesureText()
在我的应用程序中,用户可以从输入栏动态添加文本或图像。文本位于跨度元素内。添加所有图像和文本后,用户可以单击按钮将其添加到画布。在向画布添加文本时,我使用measureText()获取文本宽度,以便将其很好地放置在图像旁边 但是当我使用它时,它返回一个巨大的数字,无论文本有多大,它都是相同的(303px)。这可能是什么原因造成的Javascript 返回大数字的mesureText(),javascript,html,canvas,Javascript,Html,Canvas,在我的应用程序中,用户可以从输入栏动态添加文本或图像。文本位于跨度元素内。添加所有图像和文本后,用户可以单击按钮将其添加到画布。在向画布添加文本时,我使用measureText()获取文本宽度,以便将其很好地放置在图像旁边 但是当我使用它时,它返回一个巨大的数字,无论文本有多大,它都是相同的(303px)。这可能是什么原因造成的 if (divEl){ ctx.clearRect(0, 0, canvas.width, canvas.height);
if (divEl){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.imageSmoothingEnabled = false;
for(var n=0; n<imgDiv.children.length; n++){
if (imgDiv.children[n].nodeName === "IMG"){
ctx.drawImage(imgDiv.children[n], prevX ,0)
prevX += imgDiv.children[n].width
console.log(imgDiv.children[n].width)
}
else if(imgDiv.children[n].nodeName === "SPAN"){
ctx.font = window.getComputedStyle(spanEl[0]).fontSize + " Open Sans"
ctx.fillText(imgDiv.children[n].innerHTML,prevX ,parseInt(window.getComputedStyle(spanEl[0]).fontSize,10))
prevX += ctx.measureText(imgDiv.children[n]).width
}
}
var imagedata = ctx.getImageData(0,0,canvas.width,canvas.height)
canvas.width = prevX
ctx.putImageData(imagedata,0,0)
}
console.log(canvas.width)
console.log(canvas.height)
console.log(imagedata)
if(divEl){
clearRect(0,0,canvas.width,canvas.height);
ctx.imageSmoothingEnabled=假;
对于(var n=0;n当您使用CSS更改画布元素的宽度时会发生什么情况?#canvas{width:999px!important}
下面是发生的情况。它使画布变大,但当检查它时,它具有相同的宽度(303 px)。当您使用CSS更改画布元素的宽度时会发生什么情况?#canvas{width:999px!important}
下面是发生的情况。它使它变大了,但当检查它时,它的宽度相同(303 px)