0
我試圖在反應組件中畫一幅畫。該組件根據傳遞給它的數組的長度繪製一條線和多個正方形,作爲道具傾斜旋轉所有這些取決於另一個道具。 我有一個循環,直到它達到第5次迭代纔會完美繪製它,然後會發生一些事情,並且它開始在旋轉後混淆上下文恢復。在該循環中只有一個值更改(initialX)在瀏覽器中調試循環,rotate方法的調用次數與還原次數相同。我很困惑這種行爲,這是一個非常簡單的畫,我看不出我的錯誤在哪裏。畫在畫布上,旋轉時做奇怪的事情
This is the same sketch without applying rotation
class Sketch extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
let canvas = document.getElementById("plano");
let detector = this.props.detector
let X, Y;
if (canvas && canvas.getContext && detector) {
inicializarCanvas(detector);
function inicializarCanvas(detector) {
let ctx = canvas.getContext("2d");
let s = getComputedStyle(canvas);
let w = s.width;
let h = s.height;
canvas.width = w.split("px")[0];
canvas.height = h.split("px")[0];
X = canvas.width/2;
Y = canvas.height/2;
//draw beam
ctx.moveTo(canvas.width/3, canvas.height/2);
ctx.lineTo(0, canvas.height/2);
ctx.strokeStyle = "#f00";
ctx.stroke();
ctx.restore();
ctx.restore();
ctx.save();
drawBlades(ctx, canvas.width, canvas.height, detector)
}
function drawBlades(ctx, x, y, detector) {
let initialX = x/3
let initialY = y/4
let thick = 20
let margin = 5
let rotation = (90 - detector.angle) * Math.PI/180
let i = 0
ctx.save();
let canvas = document.getElementById("plano");
let ctx2 = canvas.getContext("2d");
ctx2.save();
console.log("blade draw")
//This loop is messing up at the 5th iteration
for (; i < detector.blades.length; i++) {
ctx2.strokeStyle = "#000000";
ctx2.translate(initialX, initialY);
ctx2.rotate(rotation);
ctx2.strokeRect(0, 0, thick, y/2);
ctx2.restore()
// this is the only variable in that changes of
// value in the loop
initialX = margin + thick + initialX
}
ctx2.save()
}
}
}
render() {
return (
<div className='sketch'>
<canvas width="400" height="150" id="plano">
Canvas not compatible with your browser
</canvas>
</div>
)
}
};
/我知道這是明顯的東西。非常感謝你 – alvcarmona
任何解釋爲什麼它正確繪製四個拳頭方格,然後它不是? – alvcarmona