[英]How to solve this canvas fillStyle problem?
class Entity { constructor(name, type = 'player') { this.name = name, this.type = type } newObject(name, ...pvals) { this[name] = {} if (pvals) { for (var i = 0; i < pvals.length; i += 2) { this[name][pvals[i]] = pvals[i + 1] } } } } const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') canvas.height = window.innerHeight - 20 canvas.width = window.innerWidth var frame = new Entity('frame', 'game-object') var button = new Entity('button', 'player-component') const radius = 70 var speed = 3 frame.newObject('$', 'r', radius) button.newObject('$', 'r', radius / 3) function updateFrame() { ctx.fillStyle = 'black' ctx.arc((canvas.width / 2), (canvas.height / 2), frame.$.r, 0, Math.PI * 2) ctx.fill() ctx.fillStyle = 'red' ctx.arc((canvas.width / 2), (canvas.height / 2), button.$.r, 0, Math.PI * 2) ctx.fill() } updateFrame()
<canvas></canvas>
据我所知,它应该在画布中间打印一个黑色的大圆圈,然后在上面打印一个红色的小圆圈。 但它只是打印一个大红色圆圈。 我就是想不通。
就像@Teemu 在评论“开始路径”中指出的那样,当你改变颜色时,你必须在你的弧之间使用ctx.beginPath()
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath#examples
我简化了很多代码以仅显示问题,当您对class Entity
进行故障排除时也应该这样做,这只是一种干扰,我们可以在没有它的情况下重现
const canvas = document.querySelector('canvas') const ctx = canvas.getContext('2d') ctx.beginPath() ctx.fillStyle = 'black' ctx.arc(50, 50, 20, 0, Math.PI * 2) ctx.fill() ctx.beginPath() ctx.fillStyle = 'red' ctx.arc(50, 50, 10, 0, Math.PI * 2) ctx.fill()
<canvas></canvas>
您应该添加以下 2 行:
ctx.beginPath();
ctx.closePath();
function updateFrame() {
ctx.beginPath();
ctx.fillStyle = 'black'
ctx.arc((canvas.width / 2), (canvas.height / 2), frame.$.r, 0, Math.PI * 2)
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.fillStyle = 'red'
ctx.arc((canvas.width / 2), (canvas.height / 2), button.$.r, 0, Math.PI * 2)
ctx.closePath();
ctx.fill()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.