찾다
웹 프론트엔드JS 튜토리얼캔버스에 검은색 배경에 빨간 불꽃놀이 만드는 법

이번에는 캔버스를 사용하여 검은 배경에 빨간색 불꽃을 만드는 방법을 보여 드리겠습니다. 캔버스를 사용하여 검은 배경에 빨간색 불꽃을 만들 때 주의 사항은 무엇입니까?

캔버스에 검은색 배경에 빨간 불꽃놀이 만드는 법

html

<canvas id="canvas"></canvas>

css

body {    background: #000;    margin: 0;
}canvas {    cursor: crosshair;    display: block;}

js

// when animating on canvas, it is best to use requestAnimationFrame instead of setTimeout or setInterval// not supported in all browsers though and sometimes needs a prefix, so we need a shimwindow.requestAnimFrame = (function () {    return window.requestAnimationFrame ||        window.webkitRequestAnimationFrame ||        window.mozRequestAnimationFrame ||        function (callback) {            window.setTimeout(callback, 1000 / 60);
        };
})();// now we will setup our basic variables for the demovar canvas = document.getElementById(&#39;canvas&#39;),
    ctx = canvas.getContext(&#39;2d&#39;),    // full screen dimensions
    cw = window.innerWidth,
    ch = window.innerHeight,    // firework collection
    fireworks = [],    // particle collection
    particles = [],    // starting hue
    hue = 120,    // when launching fireworks with a click, too many get launched at once without a limiter, one launch per 5 loop ticks
    limiterTotal = 5,
    limiterTick = 0,    // this will time the auto launches of fireworks, one launch per 80 loop ticks
    timerTotal = 80,
    timerTick = 0,
    mousedown = false,    // mouse x coordinate,
    mx,    // mouse y coordinate
    my;// set canvas dimensionscanvas.width = cw;
canvas.height = ch;// now we are going to setup our function placeholders for the entire demo// get a random number within a rangefunction random(min, max) {    return Math.random() * (max - min) + min;
}// calculate the distance between two pointsfunction calculateDistance(p1x, p1y, p2x, p2y) {    var xDistance = p1x - p2x,
        yDistance = p1y - p2y;    return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}// create fireworkfunction Firework(sx, sy, tx, ty) {    // actual coordinates
    this.x = sx;    this.y = sy;    // starting coordinates
    this.sx = sx;    this.sy = sy;    // target coordinates
    this.tx = tx;    this.ty = ty;    // distance from starting point to target
    this.distanceToTarget = calculateDistance(sx, sy, tx, ty);    this.distanceTraveled = 0;    // track the past coordinates of each firework to create a trail effect, increase the coordinate count to create more prominent trails
    this.coordinates = [];    this.coordinateCount = 3;    // populate initial coordinate collection with the current coordinates
    while (this.coordinateCount--) {        this.coordinates.push([this.x, this.y]);
    }    this.angle = Math.atan2(ty - sy, tx - sx);    this.speed = 2;    this.acceleration = 1.05;    this.brightness = random(50, 70);    // circle target indicator radius
    this.targetRadius = 1;
}// update fireworkFirework.prototype.update = function (index) {    // remove last item in coordinates array
    this.coordinates.pop();    // add current coordinates to the start of the array
    this.coordinates.unshift([this.x, this.y]);    // cycle the circle target indicator radius
    if (this.targetRadius < 8) {        this.targetRadius += 0.3;
    } else {        this.targetRadius = 1;
    }    // speed up the firework
    this.speed *= this.acceleration;    // get the current velocities based on angle and speed
    var vx = Math.cos(this.angle) * this.speed,
        vy = Math.sin(this.angle) * this.speed;    // how far will the firework have traveled with velocities applied?
    this.distanceTraveled = calculateDistance(this.sx, this.sy, this.x + vx, this.y + vy);    // if the distance traveled, including velocities, is greater than the initial distance to the target, then the target has been reached
    if (this.distanceTraveled >= this.distanceToTarget) {
        createParticles(this.tx, this.ty);        // remove the firework, use the index passed into the update function to determine which to remove
        fireworks.splice(index, 1);
    } else {        // target not reached, keep traveling
        this.x += vx;        this.y += vy;
    }
}// draw fireworkFirework.prototype.draw = function () {
    ctx.beginPath();    // move to the last tracked coordinate in the set, then draw a line to the current x and y
    ctx.moveTo(this.coordinates[this.coordinates.length - 1][0], this.coordinates[this.coordinates.length - 1][        1
    ]);
    ctx.lineTo(this.x, this.y);
    ctx.strokeStyle = &#39;hsl(&#39; + hue + &#39;, 100%, &#39; + this.brightness + &#39;%)&#39;;
    ctx.stroke();
    ctx.beginPath();    // draw the target for this firework with a pulsing circle
    ctx.arc(this.tx, this.ty, this.targetRadius, 0, Math.PI * 2);
    ctx.stroke();
}// create particlefunction Particle(x, y) {    this.x = x;    this.y = y;    // track the past coordinates of each particle to create a trail effect, increase the coordinate count to create more prominent trails
    this.coordinates = [];    this.coordinateCount = 5;    while (this.coordinateCount--) {        this.coordinates.push([this.x, this.y]);
    }    // set a random angle in all possible directions, in radians
    this.angle = random(0, Math.PI * 2);    this.speed = random(1, 10);    // friction will slow the particle down
    this.friction = 0.95;    // gravity will be applied and pull the particle down
    this.gravity = 1;    // set the hue to a random number +-20 of the overall hue variable
    this.hue = random(hue - 20, hue + 20);    this.brightness = random(50, 80);    this.alpha = 1;    // set how fast the particle fades out
    this.decay = random(0.015, 0.03);
}// update particleParticle.prototype.update = function (index) {    // remove last item in coordinates array
    this.coordinates.pop();    // add current coordinates to the start of the array
    this.coordinates.unshift([this.x, this.y]);    // slow down the particle
    this.speed *= this.friction;    // apply velocity
    this.x += Math.cos(this.angle) * this.speed;    this.y += Math.sin(this.angle) * this.speed + this.gravity;    // fade out the particle
    this.alpha -= this.decay;    // remove the particle once the alpha is low enough, based on the passed in index
    if (this.alpha <= this.decay) {
        particles.splice(index, 1);
    }
}// draw particleParticle.prototype.draw = function () {
    ctx.beginPath();    // move to the last tracked coordinates in the set, then draw a line to the current x and y
    ctx.moveTo(this.coordinates[this.coordinates.length - 1][0], this.coordinates[this.coordinates.length - 1][        1
    ]);
    ctx.lineTo(this.x, this.y);
    ctx.strokeStyle = &#39;hsla(&#39; + this.hue + &#39;, 100%, &#39; + this.brightness + &#39;%, &#39; + this.alpha + &#39;)&#39;;
    ctx.stroke();
}// create particle group/explosionfunction createParticles(x, y) {    // increase the particle count for a bigger explosion, beware of the canvas performance hit with the increased particles though
    var particleCount = 30;    while (particleCount--) {
        particles.push(new Particle(x, y));
    }
}// main demo loopfunction loop() {    // this function will run endlessly with requestAnimationFrame
    requestAnimFrame(loop);    // increase the hue to get different colored fireworks over time
    hue += 0.5;    // normally, clearRect() would be used to clear the canvas
    // we want to create a trailing effect though
    // setting the composite operation to destination-out will allow us to clear the canvas at a specific opacity, rather than wiping it entirely
    ctx.globalCompositeOperation = &#39;destination-out&#39;;    // decrease the alpha property to create more prominent trails
    ctx.fillStyle = &#39;rgba(0, 0, 0, 0.5)&#39;;
    ctx.fillRect(0, 0, cw, ch);    // change the composite operation back to our main mode
    // lighter creates bright highlight points as the fireworks and particles overlap each other
    ctx.globalCompositeOperation = &#39;lighter&#39;;    var text = "HAPPY NEW YEAR !";
    ctx.font = "50px sans-serif";    var textData = ctx.measureText(text);
    ctx.fillStyle = "rgba(" + parseInt(random(0, 255)) + "," + parseInt(random(0, 255)) + "," + parseInt(random(0,        255)) + ",0.3)";
    ctx.fillText(text, cw / 2 - textData.width / 2, ch / 2);    // loop over each firework, draw it, update it
    var i = fireworks.length;    while (i--) {
        fireworks[i].draw();
        fireworks[i].update(i);
    }    // loop over each particle, draw it, update it
    var i = particles.length;    while (i--) {
        particles[i].draw();
        particles[i].update(i);
    }    // launch fireworks automatically to random coordinates, when the mouse isn&#39;t down
    if (timerTick >= timerTotal) {        if (!mousedown) {            // start the firework at the bottom middle of the screen, then set the random target coordinates, the random y coordinates will be set within the range of the top half of the screen
            for (var h = 0; h < 50; h++) {
                fireworks.push(new Firework(cw / 2, ch / 2, random(0, cw), random(0, ch)));
            }
            timerTick = 0;
        }
    } else {
        timerTick++;
    }    // limit the rate at which fireworks get launched when mouse is down
    if (limiterTick >= limiterTotal) {        if (mousedown) {            // start the firework at the bottom middle of the screen, then set the current mouse coordinates as the target
            fireworks.push(new Firework(cw / 2, ch / 2, mx, my));
            limiterTick = 0;
        }
    } else {
        limiterTick++;
    }
}// mouse event bindings// update the mouse coordinates on mousemovecanvas.addEventListener(&#39;mousemove&#39;, function (e) {
    mx = e.pageX - canvas.offsetLeft;
    my = e.pageY - canvas.offsetTop;
});// toggle mousedown state and prevent canvas from being selectedcanvas.addEventListener(&#39;mousedown&#39;, function (e) {
    e.preventDefault();
    mousedown = true;
});
canvas.addEventListener(&#39;mouseup&#39;, function (e) {
    e.preventDefault();
    mousedown = false;
});// once the window loads, we are ready for some fireworks!window.onload = loop;

이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사에 주목하세요.

추천 도서:

JS의 async/await

React.js의 CSS 사용법

위 내용은 캔버스에 검은색 배경에 빨간 불꽃놀이 만드는 법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬과 자바 스크립트의 미래 : 트렌드와 예측파이썬과 자바 스크립트의 미래 : 트렌드와 예측Apr 27, 2025 am 12:21 AM

Python 및 JavaScript의 미래 추세에는 다음이 포함됩니다. 1. Python은 과학 컴퓨팅 분야에서의 위치를 ​​통합하고 AI, 2. JavaScript는 웹 기술의 개발을 촉진하고, 3. 교차 플랫폼 개발이 핫한 주제가되고 4. 성능 최적화가 중점을 둘 것입니다. 둘 다 해당 분야에서 응용 프로그램 시나리오를 계속 확장하고 성능이 더 많은 혁신을 일으킬 것입니다.

Python vs. JavaScript : 개발 환경 및 도구Python vs. JavaScript : 개발 환경 및 도구Apr 26, 2025 am 12:09 AM

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

JavaScript가 C로 작성 되었습니까? 증거를 검토합니다JavaScript가 C로 작성 되었습니까? 증거를 검토합니다Apr 25, 2025 am 12:15 AM

예, JavaScript의 엔진 코어는 C로 작성되었습니다. 1) C 언어는 효율적인 성능과 기본 제어를 제공하며, 이는 JavaScript 엔진 개발에 적합합니다. 2) V8 엔진을 예를 들어, 핵심은 C로 작성되며 C의 효율성 및 객체 지향적 특성을 결합하여 C로 작성됩니다.

JavaScript의 역할 : 웹 대화식 및 역동적 인 웹JavaScript의 역할 : 웹 대화식 및 역동적 인 웹Apr 24, 2025 am 12:12 AM

JavaScript는 웹 페이지의 상호 작용과 역학을 향상시키기 때문에 현대 웹 사이트의 핵심입니다. 1) 페이지를 새로 고치지 않고 콘텐츠를 변경할 수 있습니다. 2) Domapi를 통해 웹 페이지 조작, 3) 애니메이션 및 드래그 앤 드롭과 같은 복잡한 대화식 효과를 지원합니다. 4) 성능 및 모범 사례를 최적화하여 사용자 경험을 향상시킵니다.

C 및 JavaScript : 연결이 설명되었습니다C 및 JavaScript : 연결이 설명되었습니다Apr 23, 2025 am 12:07 AM

C 및 JavaScript는 WebAssembly를 통한 상호 운용성을 달성합니다. 1) C 코드는 WebAssembly 모듈로 컴파일되어 컴퓨팅 전력을 향상시키기 위해 JavaScript 환경에 도입됩니다. 2) 게임 개발에서 C는 물리 엔진 및 그래픽 렌더링을 처리하며 JavaScript는 게임 로직 및 사용자 인터페이스를 담당합니다.

웹 사이트에서 앱으로 : 다양한 JavaScript 애플리케이션웹 사이트에서 앱으로 : 다양한 JavaScript 애플리케이션Apr 22, 2025 am 12:02 AM

JavaScript는 웹 사이트, 모바일 응용 프로그램, 데스크탑 응용 프로그램 및 서버 측 프로그래밍에서 널리 사용됩니다. 1) 웹 사이트 개발에서 JavaScript는 HTML 및 CSS와 함께 DOM을 운영하여 동적 효과를 달성하고 jQuery 및 React와 같은 프레임 워크를 지원합니다. 2) 반응 및 이온 성을 통해 JavaScript는 크로스 플랫폼 모바일 애플리케이션을 개발하는 데 사용됩니다. 3) 전자 프레임 워크를 사용하면 JavaScript가 데스크탑 애플리케이션을 구축 할 수 있습니다. 4) node.js는 JavaScript가 서버 측에서 실행되도록하고 동시 요청이 높은 높은 요청을 지원합니다.

Python vs. JavaScript : 사용 사례 및 응용 프로그램 비교Python vs. JavaScript : 사용 사례 및 응용 프로그램 비교Apr 21, 2025 am 12:01 AM

Python은 데이터 과학 및 자동화에 더 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 더 적합합니다. 1. Python은 데이터 처리 및 모델링을 위해 Numpy 및 Pandas와 같은 라이브러리를 사용하여 데이터 과학 및 기계 학습에서 잘 수행됩니다. 2. 파이썬은 간결하고 자동화 및 스크립팅이 효율적입니다. 3. JavaScript는 프론트 엔드 개발에 없어서는 안될 것이며 동적 웹 페이지 및 단일 페이지 응용 프로그램을 구축하는 데 사용됩니다. 4. JavaScript는 Node.js를 통해 백엔드 개발에 역할을하며 전체 스택 개발을 지원합니다.

JavaScript 통역사 및 컴파일러에서 C/C의 역할JavaScript 통역사 및 컴파일러에서 C/C의 역할Apr 20, 2025 am 12:01 AM

C와 C는 주로 통역사와 JIT 컴파일러를 구현하는 데 사용되는 JavaScript 엔진에서 중요한 역할을합니다. 1) C는 JavaScript 소스 코드를 구문 분석하고 추상 구문 트리를 생성하는 데 사용됩니다. 2) C는 바이트 코드 생성 및 실행을 담당합니다. 3) C는 JIT 컴파일러를 구현하고 런타임에 핫스팟 코드를 최적화하고 컴파일하며 JavaScript의 실행 효율을 크게 향상시킵니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는