캔버스에 검은색 배경에 빨간 불꽃놀이 만드는 법
이번에는 캔버스를 사용하여 검은 배경에 빨간색 불꽃을 만드는 방법을 보여 드리겠습니다. 캔버스를 사용하여 검은 배경에 빨간색 불꽃을 만들 때 주의 사항은 무엇입니까?
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('canvas'), ctx = canvas.getContext('2d'), // 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 = 'hsl(' + hue + ', 100%, ' + this.brightness + '%)'; 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 = 'hsla(' + this.hue + ', 100%, ' + this.brightness + '%, ' + this.alpha + ')'; 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 = 'destination-out'; // decrease the alpha property to create more prominent trails ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'; 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 = 'lighter'; 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'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('mousemove', function (e) { mx = e.pageX - canvas.offsetLeft; my = e.pageY - canvas.offsetTop; });// toggle mousedown state and prevent canvas from being selectedcanvas.addEventListener('mousedown', function (e) { e.preventDefault(); mousedown = true; }); canvas.addEventListener('mouseup', function (e) { e.preventDefault(); mousedown = false; });// once the window loads, we are ready for some fireworks!window.onload = loop;
이 기사의 사례를 읽으신 후 방법을 마스터하셨다고 생각합니다. 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사에 주목하세요.
추천 도서:
위 내용은 캔버스에 검은색 배경에 빨간 불꽃놀이 만드는 법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

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

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

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

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

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Microsoft는 새로운 그림판 응용 프로그램을 테스트하고 경험하기 위해 Canary 및 Dev 채널의 WindowsInsider 프로젝트 멤버를 초대합니다. 최신 버전 번호는 11.2306.30.0입니다. 이번 버전 업데이트에서 가장 주목할 만한 새로운 기능은 원클릭 컷아웃 기능입니다. 사용자는 한 번만 클릭하면 자동으로 배경이 제거되고 사진의 본문이 강조 표시되므로 사용자가 후속 작업을 더 쉽게 수행할 수 있습니다. 전체 단계는 매우 간단합니다. 사용자는 새 레이아웃 응용 프로그램에서 그림을 가져온 다음 도구 모음에서 "배경 제거" 버튼을 클릭하여 그림의 배경을 삭제할 수도 있습니다. 배경.

win11의 기본 하단 작업 표시줄은 더 아름다운 하늘색입니다. 그러나 일부 친구들은 win11의 하단 상태 표시줄이 갑자기 검은색으로 변했다는 사실을 발견했습니다. 이는 테마나 배경색이 변경되었기 때문일 수 있습니다. win11 하단의 상태 표시줄이 검은색으로 변합니다. 1. 먼저 하단 시작 메뉴를 클릭하고 "설정"을 엽니다. 2. 그런 다음 왼쪽 열에 "개인 설정" 설정을 입력합니다. 3. 그런 다음 "색상" 설정을 엽니다. 4. 입력 후 "투명도 효과"를 끕니다. (켜져 있으면 데스크탑이 검은색이고 상태 표시줄이 검은색이 됩니다.) 5. 배경화면이 검은색이 아닌 경우 선택 모드를 "밝은 색상"으로 변경합니다. . 할 수 있다. 6. 다른 색상이 마음에 드시면 테마 색상 중에서 자유롭게 선택하실 수 있습니다.

1. Meitu Xiu Xiu 소프트웨어를 열고 [사진 미화]를 선택한 다음 앨범에서 사진을 가져옵니다. 2. 하단 툴바에서 [잘라내기]를 클릭한 후 [배경 교체] 기능을 선택하세요. 3. [배경] 항목의 단색 상자에서 원하는 배경색을 선택하거나 사용자 정의 이미지를 업로드하세요. 4. 선택 내용을 확인한 후 [저장]을 클릭하면 배경색 변경이 완료됩니다.

PPT 배경 교체는 프레젠테이션의 시각적 스타일을 빠르게 통일할 수 있는 중요한 작업입니다. 슬라이드 마스터를 수정하거나 배경 서식 기능을 사용하여 전체 프레젠테이션의 배경을 빠르게 바꿀 수 있습니다. 또한 일부 PPT 버전에서는 일괄 교체 기능도 제공하여 모든 슬라이드의 배경을 쉽게 교체할 수 있습니다. 배경을 교체할 때는 프레젠테이션 주제에 맞는 배경 선택에 주의해야 하며, 배경 선명도와 해상도가 요구 사항을 충족하는지 확인해야 합니다.

Canvas 프레임워크 탐색: 일반적으로 사용되는 Canvas 프레임워크가 무엇인지 이해하려면 특정 코드 예제가 필요합니다. 소개: Canvas는 풍부한 그래픽 및 애니메이션 효과를 얻을 수 있는 HTML5에서 제공되는 그리기 API입니다. 그리기의 효율성과 편의성을 향상시키기 위해 많은 개발자들이 다양한 Canvas 프레임워크를 개발했습니다. 이 기사에서는 일반적으로 사용되는 몇 가지 캔버스 프레임워크를 소개하고 독자가 이러한 프레임워크를 사용하는 방법을 더 깊이 이해하는 데 도움이 되는 특정 코드 예제를 제공합니다. 1. EaselJS 프레임워크 Ea

uniapp에서 캔버스를 사용하여 차트와 애니메이션 효과를 그리는 방법에는 특정 코드 예제가 필요합니다. 1. 소개 모바일 장치의 인기로 인해 점점 더 많은 응용 프로그램이 모바일 단말기에 다양한 차트와 애니메이션 효과를 표시해야 합니다. Vue.js를 기반으로 하는 크로스 플랫폼 개발 프레임워크인 uniapp은 캔버스를 사용하여 차트와 애니메이션 효과를 그리는 기능을 제공합니다. 이 기사에서는 uniapp이 캔버스를 사용하여 차트 및 애니메이션 효과를 구현하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 2. 캔버스

Go 언어는 C++의 복잡성과 동시성 지원 부족 문제를 해결하기 위해 Google에서 탄생했습니다. 원래 의도는 프로그래머 생산성을 향상시키고 안정적이고 확장 가능한 시스템을 구축하며 코드 포팅 및 공유를 촉진하기 위해 간단하고 배우기 쉽고 효율적인 동시성, 메모리 안전, 크로스 플랫폼 언어를 만드는 것입니다.

html2canvas 버전에는 html2canvas v0.x, html2canvas v1.x 등이 포함됩니다. 자세한 소개: 1. html2canvas v0.x는 html2canvas의 초기 버전입니다. 최신 안정 버전은 v0.5.0-alpha1입니다. 2. html2canvas v1.x는 html2canvas의 새 버전입니다.
