Canvas 当我有响应宽度和高度的画布时,html5画布的问题无法呈现矩形

Canvas 当我有响应宽度和高度的画布时,html5画布的问题无法呈现矩形,canvas,Canvas,当我有响应宽度和高度的画布时,html5画布的问题无法呈现矩形 代码中显示了exlample。 若我删除了代码的响应部分,它会呈现矩形,但矩形并没有呈现,并且无法理解为什么 const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') canvas.width = innerWidth canvas.height = innerHeight - 100 ctx.strokeRect(

当我有响应宽度和高度的画布时,html5画布的问题无法呈现矩形 代码中显示了exlample。 若我删除了代码的响应部分,它会呈现矩形,但矩形并没有呈现,并且无法理解为什么

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')


canvas.width = innerWidth
canvas.height = innerHeight - 100


ctx.strokeRect(50, 50, 50, 50);


// without this part of code it renders rectangle but with it rectangle is not rendered
window.addEventListener('resize', resizeWindow)

function resizeWindow() {
    canvas.width = innerWidth
    canvas.height = innerHeight - 100
}
resizeWindow()


这回答了你的问题吗?是的,我知道它为什么不工作了。设置canvas.width或height(即使是相同的值)会将画布2D上下文状态重置为默认值。这包括已清除的渲染内容,并且像素都设置为透明(如果创建2D上下文时
alpha:false,则为黑色)