찾다
웹 프론트엔드H5 튜토리얼캔버스에 특수 효과 잔해 불꽃놀이를 사용하여 검정색 배경을 만드는 방법

이번에는 캔버스를 활용한 검정색 배경과 특수효과로 빵 부스러기 불꽃놀이를 만드는 방법을 보여드리겠습니다. 봐.

<canvas id="cas" style="
background-color
:rgba(0,5,24,1)" width="1235" height="680">浏览器不支持canvas</canvas><div class="city">
    <img src="/static/imghwm/default1.png"  data-src="city.png"  class="lazy"   alt=""></div><img src="/static/imghwm/default1.png"  data-src="moon.png"  class="lazy"   alt="" id="moon" style="
visibility
: hidden;"><div style="display:none">
    <div class="shape">新年快乐</div>
    <div class="shape">阖家欢乐</div>
    <div class="shape">万事如意</div>
    <div class="shape">心想事成</div>
 </div>
css

body { 여백: 0; 오버플로: 숨김;

}.city { 너비: 100%; z-index: 100;

}.city img width: 100%;
}



js

var canvas = document.getElementById("cas");var ocas = document.createElement("canvas");var octx = ocas.getContext("2d");var ctx = canvas.getContext("2d");
ocas.width = canvas.width = window.innerWidth;
ocas.height = canvas.height = window.innerHeight;var bigbooms = [];window.onload = function () {
    initAnimate()
}function initAnimate() {
    drawBg();
    lastTime = new Date();
    animate();
}var lastTime;function animate() {
    ctx.save();
    ctx.fillStyle = "rgba(0,5,24,0.1)";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.restore();    var newTime = new Date();    if (newTime - lastTime > 500 + (window.innerHeight - 767) / 2) {        var random = Math.random() * 100 > 2 ? true : false;        var x = getRandom(canvas.width / 5, canvas.width * 4 / 5);        var y = getRandom(50, 200);        if (random) {            var bigboom = new Boom(getRandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#FFF", {                x: x,                y: y
            });
            bigbooms.push(bigboom)
        } else {            var bigboom = new Boom(getRandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#FFF", {                x: canvas.width / 2,                y: 200
            }, document.querySelectorAll(".shape")[parseInt(getRandom(0, document.querySelectorAll(                ".shape").length))]);
            bigbooms.push(bigboom)
        }
        lastTime = newTime;
    }
    stars.foreach(function () {        this.paint();
    })
    drawMoon();
    bigbooms.foreach(function (index) {        var that = this;        if (!this.dead) {            this._move();            this._drawLight();
        } else {            this.booms.foreach(function (index) {                if (!this.dead) {                    this.moveTo(index);
                } else if (index === that.booms.length - 1) {
                    bigbooms[bigbooms.indexOf(that)] = null;
                }
            })
        }
    });
    raf(animate);
}function drawMoon() {    var moon = document.getElementById("moon");    var centerX = canvas.width - 200,
        centerY = 100,
        width = 80;    if (moon.complete) {
        ctx.drawImage(moon, centerX, centerY, width, width)
    } else {
        moon.onload = function () {
            ctx.drawImage(moon, centerX, centerY, width, width)
        }
    }    var index = 0;    for (var i = 0; i < 10; i++) {
        ctx.save();
        ctx.beginPath();
        ctx.arc(centerX + width / 2, centerY + width / 2, width / 2 + index, 0, 2 * Math.PI);
        ctx.fillStyle = "rgba(240,219,120,0.005)";
        index += 2;
        ctx.fill();
        ctx.restore();
    }
}Array.prototype.foreach = function (callback) {    for (var i = 0; i < this.length; i++) {        if (this[i] !== null) callback.apply(this[i], [i])
    }
}var raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||    window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {        window.setTimeout(callback, 1000 / 60);
    };
canvas.onclick = function () {    var x = event.clientX;    var y = event.clientY;    var bigboom = new Boom(getRandom(canvas.width / 3, canvas.width * 2 / 3), 2, "#FFF", {        x: x,        y: y
    });
    bigbooms.push(bigboom)
}var Boom = function (x, r, c, boomArea, shape) {    this.booms = [];    this.x = x;    this.y = (canvas.height + r);    this.r = r;    this.c = c;    this.shape = shape || false;    this.boomArea = boomArea;    this.theta = 0;    this.dead = false;    this.ba = parseInt(getRandom(80, 200));
}
Boom.prototype = {    _paint: function () {
        ctx.save();
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
        ctx.fillStyle = this.c;
        ctx.fill();
        ctx.restore();
    },    _move: function () {        var dx = this.boomArea.x - this.x,
            dy = this.boomArea.y - this.y;        this.x = this.x + dx * 0.01;        this.y = this.y + dy * 0.01;        if (Math.abs(dx) <= this.ba && Math.abs(dy) <= this.ba) {            if (this.shape) {                this._shapBoom();
            } else this._boom();            this.dead = true;
        } else {            this._paint();
        }
    },    _drawLight: function () {
        ctx.save();
        ctx.fillStyle = "rgba(255,228,150,0.3)";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r + 3 * Math.random() + 1, 0, 2 * Math.PI);
        ctx.fill();
        ctx.restore();
    },    _boom: function () {        var fragNum = getRandom(30, 200);        var style = getRandom(0, 10) >= 5 ? 1 : 2;        var color;        if (style === 1) {
            color = {                a: parseInt(getRandom(128, 255)),                b: parseInt(getRandom(128, 255)),                c: parseInt(getRandom(128, 255))
            }
        }        var fanwei = parseInt(getRandom(300, 400));        for (var i = 0; i < fragNum; i++) {            if (style === 2) {
                color = {                    a: parseInt(getRandom(128, 255)),                    b: parseInt(getRandom(128, 255)),                    c: parseInt(getRandom(128, 255))
                }
            }            var a = getRandom(-Math.PI, Math.PI);            var x = getRandom(0, fanwei) * Math.cos(a) + this.x;            var y = getRandom(0, fanwei) * Math.sin(a) + this.y;            var radius = getRandom(0, 2)            var frag = new Frag(this.x, this.y, radius, color, x, y);            this.booms.push(frag);
        }
    },    _shapBoom: function () {        var that = this;
        putValue(ocas, octx, this.shape, 5, function (dots) {            var dx = canvas.width / 2 - that.x;            var dy = canvas.height / 2 - that.y;            for (var i = 0; i < dots.length; i++) {
                color = {                    a: dots[i].a,                    b: dots[i].b,                    c: dots[i].c
                }                var x = dots[i].x;                var y = dots[i].y;                var radius = 1;                var frag = new Frag(that.x, that.y, radius, color, x - dx, y - dy);
                that.booms.push(frag);
            }
        })
    }
}function putValue(canvas, context, ele, dr, callback) {
    context.clearRect(0, 0, canvas.width, canvas.height);    var img = new Image();    if (ele.innerHTML.indexOf("img") >= 0) {
        img.src = ele.
getElementsByTagName
("img")[0].src;
        imgload(img, function () {
            context.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.width / 2);
            dots = getimgData(canvas, context, dr);
            callback(dots);
        })
    } else {        var text = ele.innerHTML;
        context.save();        var fontSize = 200;
        context.font = fontSize + "px 宋体 bold";
        context.textAlign = "center";
        context.textBaseline = "middle";
        context.fillStyle = "rgba(" + parseInt(getRandom(128, 255)) + "," + parseInt(getRandom(128, 255)) + "," +            parseInt(getRandom(128, 255)) + " , 1)";
        context.fillText(text, canvas.width / 2, canvas.height / 2);
        context.restore();
        dots = getimgData(canvas, context, dr);
        callback(dots);
    }
}function imgload(img, callback) {    if (img.complete) {
        callback.call(img);
    } else {
        img.onload = function () {
            callback.call(this);
        }
    }
}function getimgData(canvas, context, dr) {    var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
    context.clearRect(0, 0, canvas.width, canvas.height);    var dots = [];    for (var x = 0; x < imgData.width; x += dr) {        for (var y = 0; y < imgData.height; y += dr) {            var i = (y * imgData.width + x) * 4;            if (imgData.data[i + 3] > 128) {                var dot = {                    x: x,                    y: y,                    a: imgData.data[i],                    b: imgData.data[i + 1],                    c: imgData.data[i + 2]
                };
                dots.push(dot);
            }
        }
    }    return dots;
}function getRandom(a, b) {    return Math.random() * (b - a) + a;
}var maxRadius = 1,
    stars = [];function drawBg() {    for (var i = 0; i < 100; i++) {        var r = Math.random() * maxRadius;        var x = Math.random() * canvas.width;        var y = Math.random() * 2 * canvas.height - canvas.height;        var star = new Star(x, y, r);
        stars.push(star);
        star.paint()
    }
}var Star = function (x, y, r) {    this.x = x;    this.y = y;    this.r = r;
}
Star.prototype = {    paint: function () {
        ctx.save();
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
        ctx.fillStyle = "rgba(255,255,255," + this.r + ")";
        ctx.fill();
        ctx.restore();
    }
}var focallength = 250;var Frag = function (centerX, centerY, radius, color, tx, ty) {    this.tx = tx;    this.ty = ty;    this.x = centerX;    this.y = centerY;    this.dead = false;    this.centerX = centerX;    this.centerY = centerY;    this.radius = radius;    this.color = color;
}
Frag.prototype = {    paint: function () {
        ctx.save();
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
        ctx.fillStyle = "rgba(" + this.color.a + "," + this.color.b + "," + this.color.c + ",1)";
        ctx.fill()
        ctx.restore();
    },    moveTo: function (index) {        this.ty = this.ty + 0.3;        var dx = this.tx - this.x,
            dy = this.ty - this.y;        this.x = Math.abs(dx) < 0.1 ? this.tx : (this.x + dx * 0.1);        this.y = Math.abs(dy) < 0.1 ? this.ty : (this.y + dy * 0.1);        if (dx === 0 && Math.abs(dy) <= 80) {            this.dead = true;
        }        this.paint();
    }
}

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

추천 자료:

캔버스에서 검정색 배경에 청록색 불꽃놀이 만드는 방법


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

위 내용은 캔버스에 특수 효과 잔해 불꽃놀이를 사용하여 검정색 배경을 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
H5 : 웹 개발을위한 새로운 기능 및 기능H5 : 웹 개발을위한 새로운 기능 및 기능Apr 29, 2025 am 12:07 AM

H5는 여러 가지 새로운 기능과 기능을 제공하여 웹 페이지의 상호 작용 및 개발 효율성을 크게 향상시킵니다. 1. Enhance SEO와 같은 시맨틱 태그. 2. 멀티미디어 지원은 오디오 및 비디오 재생 및 태그를 단순화합니다. 3. 캔버스 드로잉은 역동적 인 그래픽 드로잉 도구를 제공합니다. 4. 로컬 스토리지는 LocalStorage 및 SessionStorage를 통해 데이터 스토리지를 단순화합니다. 5. Geolocation API는 위치 기반 서비스의 개발을 용이하게합니다.

H5 : HTML5의 주요 개선H5 : HTML5의 주요 개선Apr 28, 2025 am 12:26 AM

HTML5는 5 가지 주요 개선 사항을 제공합니다. 1. 시맨틱 태그는 코드 선명도 및 SEO 효과를 향상시킵니다. 2. 멀티미디어 지원은 비디오 및 오디오 임베딩을 단순화합니다. 3. 형태 향상은 검증을 단순화한다. 4. 오프라인 및 로컬 스토리지는 사용자 경험을 향상시킵니다. 5. 캔버스 및 그래픽 기능은 웹 페이지의 시각화를 향상시킵니다.

HTML5 : 표준과 웹 개발에 미치는 영향HTML5 : 표준과 웹 개발에 미치는 영향Apr 27, 2025 am 12:12 AM

HTML5의 핵심 기능에는 시맨틱 태그, 멀티미디어 지원, 오프라인 저장 및 로컬 스토리지 및 형태 향상이 포함됩니다. 1. 코드 가독성 및 SEO 효과를 향상시키는 시맨틱 태그 등. 2. 레이블로 멀티미디어 임베딩을 단순화하십시오. 3. ApplicationCache 및 LocalStorage와 같은 오프라인 스토리지 및 로컬 스토리지는 네트워크없는 작동 및 데이터 저장을 지원합니다. 4. 양식 향상은 처리 및 검증을 단순화하기 위해 새로운 입력 유형 및 검증 속성을 도입합니다.

H5 코드 예제 : 실제 응용 프로그램 및 튜토리얼H5 코드 예제 : 실제 응용 프로그램 및 튜토리얼Apr 25, 2025 am 12:10 AM

H5는 다양한 새로운 기능과 기능을 제공하여 프론트 엔드 개발 기능을 크게 향상시킵니다. 1. 멀티미디어 지원 : 미디어를 포함하고 요소를 포함하여 플러그인이 필요하지 않습니다. 2. 캔버스 : 요소를 사용하여 2D 그래픽 및 애니메이션을 동적으로 렌더링합니다. 3. 로컬 스토리지 : LocalStorage 및 SessionStorage를 통해 지속적인 데이터 저장을 구현하여 사용자 경험을 향상시킵니다.

H5와 HTML5 사이의 연결 : 유사성과 차이H5와 HTML5 사이의 연결 : 유사성과 차이Apr 24, 2025 am 12:01 AM

H5 및 HTML5는 다른 개념입니다. HTML5는 새로운 요소 및 API를 포함하는 HTML의 버전입니다. H5는 HTML5를 기반으로 한 모바일 애플리케이션 개발 프레임 워크입니다. HTML5는 브라우저를 통해 코드를 구문 분석하고 렌더링하는 반면 H5 응용 프로그램은 컨테이너를 실행하고 JavaScript를 통해 기본 코드와 상호 작용해야합니다.

H5 코드의 빌딩 블록 : 주요 요소 및 그 목적H5 코드의 빌딩 블록 : 주요 요소 및 그 목적Apr 23, 2025 am 12:09 AM

HTML5의 주요 요소에는 최신 웹 페이지를 작성하는 데 사용되는 ,,,,, 등이 포함됩니다. 1. 헤드 컨텐츠 정의, 2. 링크를 탐색하는 데 사용됩니다. 3. 독립 기사의 내용을 나타내고, 4. 페이지 내용을 구성하고, 5. 사이드 바 컨텐츠 표시, 6. 바닥 글을 정의하면, 이러한 요소는 웹 페이지의 구조와 기능을 향상시킵니다.

HTML5 및 H5 : 일반적인 사용법 이해HTML5 및 H5 : 일반적인 사용법 이해Apr 22, 2025 am 12:01 AM

HTML5와 H5 사이에는 차이가 없으며, 이는 HTML5의 약어입니다. 1.HTML5는 HTML의 다섯 번째 버전으로 웹 페이지의 멀티미디어 및 대화식 기능을 향상시킵니다. 2.H5는 종종 HTML5 기반 모바일 웹 페이지 또는 응용 프로그램을 참조하는 데 사용되며 다양한 모바일 장치에 적합합니다.

HTML5 : 현대 웹의 빌딩 블록 (H5)HTML5 : 현대 웹의 빌딩 블록 (H5)Apr 21, 2025 am 12:05 AM

HTML5는 W3C에 의해 표준화 된 하이퍼 텍스트 마크 업 언어의 최신 버전입니다. HTML5는 새로운 시맨틱 태그, 멀티미디어 지원 및 양식 향상을 도입하여 웹 구조, 사용자 경험 및 SEO 효과를 개선합니다. HTML5는 웹 페이지 구조를 더 명확하게하고 SEO 효과를 더 좋게하기 위해, 등 등과 같은 새로운 시맨틱 태그를 소개합니다. HTML5는 멀티미디어 요소를 지원하며 타사 플러그인이 필요하지 않으므로 사용자 경험을 향상시키고 속도를로드합니다. HTML5는 양식 함수를 향상시키고 사용자 경험을 향상시키고 양식 검증 효율성을 향상시키는 새로운 입력 유형을 도입합니다.

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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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