캔버스에 불꽃 놀이를 만들었습니다. 이것을 캔버스 안의 임의의 위치에 복제하고 싶습니다.
마지막으로 임의의 위치에서 임의의 순서로 실행하고 싶습니다. 무엇을 더 추가해야합니까?
var ctx = document.getElementById('canvas').getContext('2d');
ctx.translate(100, 100);
function fireworks() {
//clipping
ctx.beginPath();
ctx.arc(0, 0, 60, 0, Math.PI * 2, true);
ctx.clip();
var x = 130; //final position
var t = 0; //0-1, this is what you change in animation loop
var tx = 0; //actual position of element for x
function myLoop() {
ctx.clearRect(-(canvas.width / 2), -(canvas.height / 2), canvas.width, canvas.height);
tx = EasingFunctions.easeInOutQuad(t) * x;
for (var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate(Math.PI / 6);
ctx.arc(tx, tx, 5, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
if (t < 1) {
t += 0.01; //determines speed
requestAnimationFrame(myLoop);
}
}
myLoop();
}
EasingFunctions = {
easeInOutQuad: function(t) {
return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
}
fireworks();
#canvas {
border: 1px solid #000;
}
<canvas id="canvas" width="800" height="600"></canvas>
솔루션에는 몇 가지 단계가 포함됩니다.
fireworks
마지막 "불꽃 놀이"가 끝나면 전화하세요 .clip
에 의해 상태 .restore()
및.save()
코드에 주석을 추가했습니다.
var ctx = document.getElementById('canvas').getContext('2d');
function fireworks() {
// restore and save to reset the "clip" state
ctx.restore();
ctx.save();
//clipping
ctx.beginPath();
// move to a random position in the canvas before drawing
ctx.translate(random(canvas.width), random(canvas.height));
ctx.arc(0, 0, 60, 0, Math.PI * 2, true);
ctx.clip();
let tx = 0; //actual position of element for x
let t = 0;
function myLoop() {
ctx.clearRect(-(canvas.width / 2), -(canvas.height / 2), canvas.width, canvas.height);
tx = EasingFunctions.easeInOutQuad(t) * 130;
for (var i = 0; i < 12; i++) {
ctx.beginPath();
ctx.rotate(Math.PI / 6);
ctx.arc(tx, tx, 5, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
if (t < 1) {
t += 0.01; //determines speed
requestAnimationFrame(myLoop);
} else {
// the firework is done, let's create another one
fireworks();
}
}
myLoop();
}
function random(max, min = 0) {
return Math.floor(Math.random() * max) + 1;
}
EasingFunctions = {
easeInOutQuad: function(t) {
return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
}
fireworks();
#canvas {
border: 1px solid #000;
}
<canvas id="canvas" width="800" height="600"></canvas>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다