折腾:
【未解决】HTML中用Canvas画文字
期间,希望设置全局的背景色是黑色
html canvas set global background color
ctx.fillStyle = "blue"; ctx.fillRect(0, 0, canvas.width, canvas.height);
此处用:
ctx.fillStyle = 'black' ctx.fillRect(0, 0, canvas.width, canvas.height)

虽然是:黑色背景了:但是后面的画的线段,都看不到了。
只能看到文字
ctx.fillStyle = 'black' ctx.fillRect(0, 0, canvas.width, canvas.height)
放到最后:

结果会导致:

前面的全部内容都被覆盖了。看不到了。
去试试:
ctx.globalCompositeOperation = 'destination-over' ctx.fillStyle = 'black' ctx.fillRect(0, 0, canvas.width, canvas.height)
结果:
问题依旧。
ctx.fillStyle = 'black'
ctx.fillRect(0, 0, canvas.width, canvas.height)
// Add behind elements.
// ctx.globalCompositeOperation = 'destination-over'
ctx.globalCompositeOperation = 'destination-out'
// ctx.fillStyle = 'green'
ctx.fillStyle = 'red'
// ctx.strokeStyle = 'green'
// ctx.strokeStyle = 'red'
ctx.lineWidth = 6
ctx.beginPath() // 新建一条path
ctx.moveTo(50, 50) // 把画笔移动到指定的坐标
ctx.lineTo(130, 50) // 绘制一条从当前位置到指定坐标(200, 50)的直线
ctx.closePath() // 闭合路径。会拉一条从当前点到path起始点的直线。如果当前点与起始点重合,则什么都不做
ctx.moveTo(230, 50)
ctx.lineTo(400, 50)
ctx.closePath()
ctx.moveTo(460, 50)
ctx.lineTo(500, 50)
ctx.closePath()
ctx.moveTo(600, 50)
ctx.lineTo(750, 50)
ctx.closePath()
ctx.stroke() // 绘制路径
ctx.fillStyle = 'white'
// ctx.strokeStyle = 'green'
// ctx.lineWidth = 10
ctx.lineWidth = 1
ctx.font = '12px 宋体'
// ctx.strokeText('进线', 270, 30)
ctx.fillText('进线', 270, 30)结果是:

有内容了,但是不是红色,而是白色
算了,暂时去用css设置吧
canvas {
border: 1px solid black;
background: black;
}和:
const canvas = document.getElementById('controlPanel')
if (canvas.getContext) {
// 获得 2d 上下文对象
const ctx = canvas.getContext('2d')
// ctx.fillStyle = 'rgb(200,0,0)'
// // 绘制矩形
// ctx.fillRect(10, 10, 55, 50)
// ctx.fillStyle = 'rgba(0, 0, 200, 0.5)'
// ctx.fillStyle = 'black'
// ctx.fillRect(0, 0, canvas.width, canvas.height)
// // Add behind elements.
// // ctx.globalCompositeOperation = 'destination-over'
// ctx.globalCompositeOperation = 'destination-out'
// ctx.fillStyle = 'green'
ctx.fillStyle = 'red'
// ctx.strokeStyle = 'green'
ctx.strokeStyle = 'red'
ctx.lineWidth = 6
ctx.beginPath() // 新建一条path
ctx.moveTo(50, 50) // 把画笔移动到指定的坐标
ctx.lineTo(130, 50) // 绘制一条从当前位置到指定坐标(200, 50)的直线
ctx.closePath() // 闭合路径。会拉一条从当前点到path起始点的直线。如果当前点与起始点重合,则什么都不做
ctx.moveTo(230, 50)
ctx.lineTo(400, 50)
ctx.closePath()
ctx.moveTo(460, 50)
ctx.lineTo(500, 50)
ctx.closePath()
ctx.moveTo(600, 50)
ctx.lineTo(750, 50)
ctx.closePath()
ctx.stroke() // 绘制路径
ctx.fillStyle = 'white'
// ctx.strokeStyle = 'green'
// ctx.lineWidth = 10
ctx.lineWidth = 1
ctx.font = '12px 宋体'
// ctx.strokeText('进线', 270, 30)
ctx.fillText('进线', 270, 30)
}即可:

【总结】
暂时用了canvas设置背景色,结果会影响后续的线条和文字的前景色或背景色,所以最后改为css设置style
canvas {
background: black;
}即可设置canvas的背景色,而不影响canvas中画的内容。
转载请注明:在路上 » 【已解决】Html的Canvas设置全局背景色