我寫了自己的多邊形函數;問題是當我想讓多邊形只繪製一個邊框時,它最終使用前面的fillStyle並繪製上一個多邊形。畫布多邊形函數在錯誤時間填充
var canvas = document.getElementById('canvas')
var ctx = canvas.getContext('2d')
const HP_DARKGREEN = '#003100'
const HP_LIGHTGREEN = '#007E00'
var health = 50
function polygon(x1, y1, border = {
color: 'black',
width: 1,
lineJoin: 'round',
lineCap: 'square'
}, fillColor = false, ...coords) {
/* Draws a polygon given an array of coordinates */
let c = coords
ctx.translate(x1, y1)
if (border) {
ctx.strokeStyle = border.color
}
ctx.beginPath()
for (let i = 0; i < c.length - 1; i += 2) {
ctx.lineTo(c[i], c[i + 1])
}
ctx.closePath()
if (fillColor) {
ctx.fillStyle = fillColor
ctx.fill()
}
if (border) {
ctx.lineWidth = border.width
ctx.lineCap = border.lineCap
ctx.lineJoin = border.lineJoin
ctx.stroke()
}
ctx.translate(-x1, -y1)
}
//Trying to draw these polygons
polygon(14, 4, false, HP_DARKGREEN, 114, 4, 104, 19, 4, 19, 14, 4)
polygon(14, 4, false, HP_LIGHTGREEN, health + 14, 4, health + 4, 19, 4, 19, 14, 4)
polygon(14, 4, {
color: 'black',
width: 2
}, false, 114, 4, 104, 19, 4, 19, 14, 4)
var Render = {
clear:() => {
ctx.clearRect(0, 0, canvas.width, canvas.height)
},
update:() => {
Render.clear()
Render.display.health()
requestAnimationFrame(() => {
Render.update()
})
}
}
<canvas id='canvas' width=192 height=192></canvas>
現在,我看它,它似乎在的jsfiddle做工精美。唯一的區別是在實際的程序中,我使用requestAnimationFrame()
來循環渲染過程。問題是由第三個多邊形引起的(它用淺綠色填充整個酒吧)。
編輯:我只是試圖在我的代碼中運行一次函數。它運行良好;當我運行循環功能時,它無法正確繪製。我不確定這是否是默認參數或其他問題的問題...
不,我可以很容易地完成。我遇到的問題是第三個多邊形(在你的案例中有紅色邊框)使整個酒吧變成綠色。這在JSFiddle中不會發生。我將嘗試添加更多代碼來重現此問題。 – adapap