찾다
웹 프론트엔드HTML 튜토리얼캔버스 스크래쳐와 브러쉬

캔버스 스크래쳐와 브러쉬

Nov 04, 2016 pm 05:26 PM
canvash5

舍不得买2块钱的刮刮乐,就只能写个类似的功能过过彩票瘾了!

布局

<div id="lottery" style="width:300px;height:500px;margin:10px;background-color:lightskyblue;border-radius:5px;float:left;">
         <div style="width:300px;height:100px;line-height:100px;text-align:center;font-size:33px;color:blueviolet;">NICK彩票</div>
         <div id="txt" style="width:300px;height:200px;font-size:40px;color:peachpuff;display:flex;justify-content:center;align-items:center;flex-direction:column;">
             <span>祝</span>
             <span>君</span>
             <span>中</span>
             <span>奖</span>
         </div>
         <div id="canvasArea" style="width:300px;height:200px;position:relative;">
             <div style="width:300px;height:200px;position:absolute;top:0;left:0;z-index:1;text-align:center;line-height:200px;font-weight:bold;font-size:56px;color:indianred;">一等奖</div>
             <canvas id="canvas" width="300px" height="200px" style="position:absolute;top:0;left:0;z-index:2;"></canvas>
         </div>
     </div>

这段html要注意的地方有2个:

flex布局,将‘祝君中奖’垂直居中,目前还有兼容问题,不过看我们大前端的发展趋势,应该很快就能搞定了;

canvas和‘一等奖’div的z-index问题,将canvas的z-index设置较高,使其置于一等奖div上面。

设置canvas画布

var canvas = document.getElementById("canvas");

var context = canvas.getContext("2d");

绘制刮奖区域

       context.fillStyle='#A9AB9D';
       context.fillRect(10,10,280,180);
       context.fillStyle='#000';
       context.font='50px Arial';
       context.fillText('刮奖区',75,115);

填充颜色;

绘制实心矩形;

设置字体颜色;

设置字体大小类型;

绘制实心字体。

以上都是canvas基础api,看w3c就ok了。

为了好看,我将‘祝君中奖’加个字体变色

        setInterval(function(){
            document.getElementById(&#39;txt&#39;).style.color = 
            document.getElementById(&#39;txt&#39;).style.color==&#39;
            peachpuff&#39; ? &#39;yellow&#39; : &#39;peachpuff&#39;;
        },500);

刮奖功能函数

        var brush=function(){//刮奖
            context.clearRect(event.offsetX,event.offsetY,20,20);
        };

为canvas元素onmousedown和onmouseup事件

复制代码

        canvas.onmousedown = function(){
            // 鼠标按下时 - 绑定鼠标跟随事件
            bindHandler(canvas,&#39;mousemove&#39;,brush,false);
        }
        canvas.onmouseup = function(){
            // 停止刮奖功能 - 解绑鼠标跟随事件
            removeHandler(canvas,"mousemove",brush,false);
        }

复制代码

这里的事件绑定与解绑我上篇博文有封装,最后完整代码也有!


刮刮乐happy到底结束!最后附上完整代码,再看看效果吧!


demo二:画笔

布局

     <div style="width:300px;height:500px;margin:10px;border-radius:10px;overflow:hidden;float:right;">
         <canvas id="canvas2" width="300px" height="500px" style="background-color:lightblue;"></canvas>
     </div>

设置canvas画布

        var canvas2 = document.getElementById("canvas2");
        var context2 = canvas2.getContext("2d");

画笔功能函数

        var draw=function(){
            context2.fillRect(event.offsetX,event.offsetY,10,10);
        };

为canvas元素onmousedown和onmouseup事件

        context2.font=&#39;20px Arial&#39;;
        context2.strokeText(&#39;NICK画笔&#39;,100,30);//写个头
        //1. 为canvas元素onmousedown和onmouseup事件
        canvas2.onmousedown = function(){
            // 启用画笔功能 - 绑定鼠标跟随事件
            bindHandler(canvas2,&#39;mousemove&#39;,draw,false);
        }
        canvas2.onmouseup = function(){
            // 停止画笔功能 - 解绑鼠标跟随事件
            removeHandler(canvas2,"mousemove",draw,false);
        }

画图工具的画笔功能到底结束!


附上完整代码:



 
  Canvas lottery brush nick
  
 
 
 
<div id="lottery" style="width:300px;height:500px;margin:10px;background-color:lightskyblue;border-radius:5px;float:left;"> <div style="width:300px;height:100px;line-height:100px;text-align:center;font-size:33px;color:blueviolet;">NICK彩票</div> <div id="txt" style="width:300px;height:200px;font-size:40px;color:peachpuff;display:flex;justify-content:center;align-items:center;flex-direction:column;"> <span>祝</span> <span>君</span> <span>中</span> <span>奖</span> </div> <div id="canvasArea" style="width:300px;height:200px;position:relative;"> <div style="width:300px;height:200px;position:absolute;top:0;left:0;z-index:1;text-align:center;line-height:200px;font-weight:bold;font-size:56px;color:indianred;">一等奖</div> <canvas id="canvas" width="300px" height="200px" style="position:absolute;top:0;left:0;z-index:2;"></canvas> </div> </div> <div style="width:300px;height:500px;margin:10px;border-radius:10px;overflow:hidden;float:right;"> <canvas id="canvas2" width="300px" height="500px" style="background-color:lightblue;"></canvas> </div>

刮刮乐:鼠标按住不放,拖动开始刮奖!

画笔:鼠标按住不放,拖动画画!

<script> //插件方法封装区 ;(function(){ // 事件绑定 window.bindHandler = (function() { if (window.addEventListener) {// 标准浏览器 return function(elem, type, handler) { // elem:节点 type:事件类型 handler:事件处理函数 // 最后一个参数为true:在捕获阶段调用事件处理程序;为false:在冒泡阶段调用事件处理程序。注意:ie没有这个参数 elem.addEventListener(type, handler, false); } } else if (window.attachEvent) {// IE浏览器 return function(elem, type, handler) { elem.attachEvent("on" + type, handler); } } }()); // 事件解除 window.removeHandler = (function() { if (window.removeEventListener) {// 标准浏览器 return function(elem, type, handler) { elem.removeEventListener(type, handler, false); } } else if (window.detachEvent) {// IE浏览器 return function(elem, type, handler) { elem.detachEvent("on" + type, handler); } } }()); }()); //命名区 var canvas = document.getElementById("canvas"); var context = canvas.getContext("2d"); var canvas2 = document.getElementById(&quot;canvas2&quot;); var context2 = canvas2.getContext(&quot;2d&quot;); var brush=function(){//刮奖 context.clearRect(event.offsetX,event.offsetY,20,20); }; var draw=function(){//写字 context2.fillRect(event.offsetX,event.offsetY,10,10); }; //功能实现区 //刮刮乐 // 1. 绘制刮奖区域 context.fillStyle=&#39;#A9AB9D&#39;; context.fillRect(10,10,280,180); context.fillStyle=&#39;#000&#39;; context.font=&#39;50px Arial&#39;; context.fillText(&#39;刮奖区&#39;,75,115); //字体变色 setInterval(function(){ document.getElementById(&#39;txt&#39;).style.color = document.getElementById(&#39;txt&#39;).style.color==&#39;peachpuff&#39; ? &#39;yellow&#39; : &#39;peachpuff&#39;; },500); //2. 为canvas元素onmousedown和onmouseup事件 canvas.onmousedown = function(){ // 鼠标按下时 - 绑定鼠标跟随事件 bindHandler(canvas,&amp;#39;mousemove&amp;#39;,brush,false); } canvas.onmouseup = function(){ // 停止刮奖功能 - 解绑鼠标跟随事件 removeHandler(canvas,&quot;mousemove&quot;,brush,false); } //画笔 context2.font=&amp;#39;20px Arial&amp;#39;; context2.strokeText(&amp;#39;NICK画笔&amp;#39;,100,30);//写个头 //1. 为canvas元素onmousedown和onmouseup事件 canvas2.onmousedown = function(){ // 启用画笔功能 - 绑定鼠标跟随事件 bindHandler(canvas2,&amp;#39;mousemove&amp;#39;,draw,false); } canvas2.onmouseup = function(){ // 停止画笔功能 - 解绑鼠标跟随事件 removeHandler(canvas2,&quot;mousemove&quot;,draw,false); } </script>




성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
HTML 태그와 HTML 속성의 차이점은 무엇입니까?HTML 태그와 HTML 속성의 차이점은 무엇입니까?May 14, 2025 am 12:01 AM

htmltagsdefinestructureofawebpage, whiletributesdfunctionalityanddetails.1) tags, andoutlinethecontent'splacement.2) agtributessuchassrc, class 및 styleenhancetagsbysingingimages ources, styling, and mormore, mormor, 개선.

HTML의 미래 : 진화와 트렌드HTML의 미래 : 진화와 트렌드May 13, 2025 am 12:01 AM

HTML의 미래는보다 의미적이고 기능적이며 모듈 식 방향으로 발전 할 것입니다. 1) 의미화로 인해 태그가 콘텐츠를보다 명확하게 설명하여 SEO 및 장벽없는 액세스를 향상시킵니다. 2) 기능화는 사용자의 요구를 충족시키기 위해 새로운 요소와 속성을 소개합니다. 3) 모듈화는 구성 요소 개발을 지원하고 코드 재사용 성을 향상시킵니다.

HTML 속성이 웹 개발에 중요한 이유는 무엇입니까?HTML 속성이 웹 개발에 중요한 이유는 무엇입니까?May 12, 2025 am 12:01 AM

htmlattributesarecrucialinwebdevelopmentforcontrollingbehavior, 외관 및 기능. 접근성, 접근성, andseo.forexample, thesrcattributeintagspactsseo, whike whike whike whike whike whike thercattributeintagspactsseo

ALT 속성의 목적은 무엇입니까? 왜 중요한가요?ALT 속성의 목적은 무엇입니까? 왜 중요한가요?May 11, 2025 am 12:01 AM

ALT 속성은 HTML에서 태그의 중요한 부분이며 이미지에 대한 대체 텍스트를 제공하는 데 사용됩니다. 1. 이미지를로드 할 수 없으면 ALT 속성의 텍스트가 표시되어 사용자 경험을 향상시킵니다. 2. 스크린 리더는 ALT 속성을 사용하여 시각 장애가있는 사용자가 그림의 내용을 이해하도록 도와줍니다. 3. 검색 엔진 인덱스 텍스트 텍스트는 웹 페이지의 SEO 순위를 향상시키기 위해 ALT 속성의 텍스트를 색인 텍스트입니다.

HTML, CSS 및 JavaScript : 예제 및 실제 응용 프로그램HTML, CSS 및 JavaScript : 예제 및 실제 응용 프로그램May 09, 2025 am 12:01 AM

웹 개발에서 HTML, CSS 및 JavaScript의 역할은 다음과 같습니다. 1. HTML은 웹 페이지 구조를 구축하는 데 사용됩니다. 2. CSS는 웹 페이지의 모양을 아름답게하는 데 사용됩니다. 3. JavaScript는 동적 상호 작용을 달성하는 데 사용됩니다. 태그, 스타일 및 스크립트를 통해이 세 가지는 함께 현대 웹 페이지의 핵심 기능을 구축합니다.

 태그에서 Lang 속성을 어떻게 설정합니까? 이것이 중요한 이유는 무엇입니까? 태그에서 Lang 속성을 어떻게 설정합니까? 이것이 중요한 이유는 무엇입니까?May 08, 2025 am 12:03 AM

태그의 Lang 속성을 설정하는 것은 웹 접근성 및 SEO를 최적화하는 핵심 단계입니다. 1) 태그에 LANG 속성을 설정하십시오. 2) 다국어 컨텐츠에서는 다른 언어 부품에 대한 LANG 속성을 설정하십시오. 3) "en", "fr", "zh"와 같은 ISO639-1 표준을 준수하는 언어 코드를 사용하여 LANG 속성을 올바르게 설정하면 웹 페이지 및 검색 엔진 순위의 접근성을 향상시킬 수 있습니다.

HTML 속성의 목적은 무엇입니까?HTML 속성의 목적은 무엇입니까?May 07, 2025 am 12:01 AM

htmlattributesearsentialforenhancingwebelements'functionalityandAmpearance.theyaddinformationTodeFineBehavior, 외관 및 간호, WebsITESITERACTIVE, RAPITIVE 및 VVESILLY -CAMENTION.ATTRIBUTESLIKESRC, HREF, 클래스, 유형 및 디스티브 트랜스포트

HTML에서 목록을 어떻게 만드나요?HTML에서 목록을 어떻게 만드나요?May 06, 2025 am 12:01 AM

ToCreateAlistInhtml, useUnorderEdListandForOrdLists : 1) forUnderedList, wrapitemSinanduseForeachitem, renderingasabulletedList.2) forOrderEdlists, useandfornumberedLists, useandfornumberedlists, useandfornumberedlists, useandfornumberedlists, withTheyPeatTributeFferentNumberingStyles.

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

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.