웹 프론트엔드 JS 튜토리얼 자바스크립트 html5 캔버스를 기반으로 브러시 색상/두께/지우개를 조정할 수 있는 그래피티 보드 구현

자바스크립트 html5 캔버스를 기반으로 브러시 색상/두께/지우개를 조정할 수 있는 그래피티 보드 구현

Mar 16, 2017 pm 01:17 PM
canvas html5

js HTML5 캔버스로 구현된 그래피티 화판 특수효과는 브러쉬 색상 | 지우개 조절이 가능하며, 그래피티 효과를 이미지 인코딩으로 저장할 수 있어 HTML5 캔버스를 학습하는데 매우 적합합니다. .

<!doctype html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>javascript结合html5 canvas实现的涂鸦板</title> 
<meta name="Copyright" content="JavaScript分享网 //m.sbmmt.com/" /> 
<meta name="description" content="javascript结合html5 canvas实现的涂鸦板,JavaScript分享网,js脚本,网页特效,网页模板,png图标,矢量图下载" /> 
<meta content="JavaScript,分享,JavaScript代码,Ajax,jQuery,网页模板,PNG图标,矢量图" name="keywords" /> 
</head> 
<body> 
<style> 
*{margin:0;padding:0;} 
.fa{width:740px;margin:0 auto;} 
.top{margin:20px 0;} 
.top input{width:25px;height:25px;border:1px solid #fff;border-radius:4px;background:#ddd;} 
.top .i1{background:#000000;} 
.top .i2{background:#FF0000;} 
.top .i3{background:#80FF00;} 
.top .i4{background:#00FFFF;} 
.top .i5{background:#808080;} 
.top .i6{background:#FF8000;} 
.top .i7{background:#408080;} 
.top .i8{background:#8000FF;} 
.top .i9{background:#CCCC00;} 
#canvas{background:#eee;cursor:default;} 
.font input{font-size:14px;} 
.top .grea{background:#aaa;} 
</style> 
</head> 
<body> 
<p class="fa"> 
<p class="top"> 
<p id="color"> 
请选择画笔颜色: 
<input class="i1" type="button" value="" /> 
<input class="i2" type="button" value="" /> 
<input class="i3" type="button" value="" /> 
<input class="i4" type="button" value="" /> 
<input class="i5" type="button" value="" /> 
<input class="i6" type="button" value="" /> 
<input class="i7" type="button" value="" /> 
<input class="i8" type="button" value="" /> 
<input class="i9" type="button" value="" /> 
</p> 
<p class="font" id="font"> 
请选择画笔的宽度: 
<input type="button" value="细" /> 
<input type="button" value="中" class="grea"/> 
<input type="button" value="粗" /> 
</p> 
<p> 
<span id="error">如果有错误,请使用橡皮擦:</span> 
<input id="eraser" style="width:60px;font-size:14px;"type="button" value="橡皮擦" /> 
</p> 
<input id="clear" type="button" value="清除画布" style="width:80px;"/> 
<input id="revocation" type="button" value="撤销" style="width:80px;"/> 
<input id="imgurl" type="button" value="导出图片路径" style="width:80px;"/> 
</p> 
<canvas id="canvas" width="740" height="420">您的浏览器不支持 canvas 标签</canvas> 
<p id="p1"></p> 
</p> 
<p id="html"> 
</p> 
<script> 
(function(){ 
var paint={ 
init:function() 
{ 
this.load(); 
}, 
load:function() 
{ 
this.x=[];//记录鼠标移动是的X坐标 
this.y=[];//记录鼠标移动是的Y坐标 
this.clickDrag=[]; 
this.lock=false;//鼠标移动前,判断鼠标是否按下 
this.isEraser=false; 
//this.Timer=null;//橡皮擦启动计时器 
//this.radius=5; 
this.storageColor="#000000"; 
this.eraserRadius=15;//擦除半径值 
this.color=["#000000","#FF0000","#80FF00","#00FFFF","#808080","#FF8000","#408080","#8000FF","#CCCC00"];//画笔颜色值 
this.fontWeight=[2,5,8]; 
this.$=function(id){return typeof id=="string"?document.getElementById(id):id;}; 
this.canvas=this.$("canvas"); 
if (this.canvas.getContext) { 
} else { 
alert("您的浏览器不支持 canvas 标签"); 
return; 
} 
this.cxt=this.canvas.getContext(&#39;2d&#39;); 
this.cxt.lineJoin = "round";//context.lineJoin - 指定两条线段的连接方式 
this.cxt.lineWidth = 5;//线条的宽度 
this.iptClear=this.$("clear"); 
this.revocation=this.$("revocation"); 
this.imgurl=this.$("imgurl");//图片路径按钮 
this.w=this.canvas.width;//取画布的宽 
this.h=this.canvas.height;//取画布的高 
this.touch =("createTouch" in document);//判定是否为手持设备 
this.StartEvent = this.touch ? "touchstart" : "mousedown";//支持触摸式使用相应的事件替代 
this.MoveEvent = this.touch ? "touchmove" : "mousemove"; 
this.EndEvent = this.touch ? "touchend" : "mouseup"; 
this.bind(); 
}, 
bind:function() 
{ 
var t=this; 
/*清除画布*/ 
this.iptClear.onclick=function() 
{ 
t.clear(); 
}; 
/*鼠标按下事件,记录鼠标位置,并绘制,解锁lock,打开mousemove事件*/ 
this.canvas[&#39;on&#39;+t.StartEvent]=function(e) 
{ 
var touch=t.touch ? e.touches[0] : e; 
var _x=touch.clientX - touch.target.offsetLeft;//鼠标在画布上的x坐标,以画布左上角为起点 
var _y=touch.clientY - touch.target.offsetTop;//鼠标在画布上的y坐标,以画布左上角为起点 
if(t.isEraser) 
{ 
/* 
t.cxt.globalCompositeOperation = "destination-out"; 
t.cxt.beginPath(); 
t.cxt.arc(_x, _y,t.eraserRadius, 0, Math.PI * 2); 
t.cxt.strokeStyle = "rgba(250,250,250,0)"; 
t.cxt.fill(); 
t.cxt.globalCompositeOperation = "source-over"; 
*/ 
t.resetEraser(_x,_y,touch); 
}else 
{ 
t.movePoint(_x,_y);//记录鼠标位置 
t.drawPoint();//绘制路线 
} 
t.lock=true; 
}; 
/*鼠标移动事件*/ 
this.canvas[&#39;on&#39;+t.MoveEvent]=function(e) 
{ 
var touch=t.touch ? e.touches[0] : e; 
if(t.lock)//t.lock为true则执行 
{ 
var _x=touch.clientX - touch.target.offsetLeft;//鼠标在画布上的x坐标,以画布左上角为起点 
var _y=touch.clientY - touch.target.offsetTop;//鼠标在画布上的y坐标,以画布左上角为起点 
if(t.isEraser) 
{ 
//if(t.Timer)clearInterval(t.Timer); 
//t.Timer=setInterval(function(){ 
t.resetEraser(_x,_y,touch); 
//},10); 
} 
else 
{ 
t.movePoint(_x,_y,true);//记录鼠标位置 
t.drawPoint();//绘制路线 
} 
} 
}; 
this.canvas[&#39;on&#39;+t.EndEvent]=function(e) 
{ 
/*重置数据*/ 
t.lock=false; 
t.x=[]; 
t.y=[]; 
t.clickDrag=[]; 
clearInterval(t.Timer); 
t.Timer=null; 
}; 
this.revocation.onclick=function() 
{ 
t.redraw(); 
}; 
this.changeColor(); 
this.imgurl.onclick=function() 
{ 
t.getUrl(); 
}; 
/*橡皮擦*/ 
this.$("eraser").onclick=function(e) 
{ 
t.isEraser=true; 
t.$("error").style.color="red"; 
t.$("error").innerHTML="您已使用橡皮擦!"; 
}; 
}, 
movePoint:function(x,y,dragging) 
{ 
/*将鼠标坐标添加到各自对应的数组里*/ 
this.x.push(x); 
this.y.push(y); 
this.clickDrag.push(y); 
}, 
drawPoint:function(x,y,radius) 
{ 
for(var i=0; i < this.x.length; i++)//循环数组 
{ 
this.cxt.beginPath();//context.beginPath() , 准备绘制一条路径 
if(this.clickDrag[i] && i){//当是拖动而且i!=0时,从上一个点开始画线。 
this.cxt.moveTo(this.x[i-1], this.y[i-1]);//context.moveTo(x, y) , 新开一个路径,并指定路径的起点 
}else{ 
this.cxt.moveTo(this.x[i]-1, this.y[i]); 
} 
this.cxt.lineTo(this.x[i], this.y[i]);//context.lineTo(x, y) , 将当前点与指定的点用一条笔直的路径连接起来 
this.cxt.closePath();//context.closePath() , 如果当前路径是打开的则关闭它 
this.cxt.stroke();//context.stroke() , 绘制当前路径 
} 
}, 
clear:function() 
{ 
this.cxt.clearRect(0, 0, this.w, this.h);//清除画布,左上角为起点 
}, 
redraw:function() 
{ 
/*撤销*/ 
this.cxt.restore(); 
}, 
preventDefault:function(e){ 
/*阻止默认*/ 
var touch=this.touch ? e.touches[0] : e; 
if(this.touch)touch.preventDefault(); 
else window.event.returnValue = false; 
}, 
changeColor:function() 
{ 
/*为按钮添加事件*/ 
var t=this,iptNum=this.$("color").getElementsByTagName("input"),fontIptNum=this.$("font").getElementsByTagName("input"); 
for(var i=0,l=iptNum.length;i<l;i++) 
{ 
iptNum[i].index=i; 
iptNum[i].onclick=function() 
{ 
t.cxt.save(); 
t.cxt.strokeStyle = t.color[this.index]; 
t.storageColor=t.color[this.index]; 
t.$("error").style.color="#000"; 
t.$("error").innerHTML="如果有错误,请使用橡皮擦:"; 
t.cxt.strokeStyle = t.storageColor; 
t.isEraser=false; 
} 
} 
for(var i=0,l=fontIptNum.length;i<l;i++) 
{ 
t.cxt.save(); 
fontIptNum[i].index=i; 
fontIptNum[i].onclick=function() 
{ 
t.changeBackground(this.index); 
t.cxt.lineWidth = t.fontWeight[this.index]; 
t.$("error").style.color="#000"; 
t.$("error").innerHTML="如果有错误,请使用橡皮擦:"; 
t.isEraser=false; 
t.cxt.strokeStyle = t.storageColor; 
} 
} 
}, 
changeBackground:function(num) 
{ 
/*添加画笔粗细的提示背景颜色切换,灰色为当前*/ 
var fontIptNum=this.$("font").getElementsByTagName("input"); 
for(var j=0,m=fontIptNum.length;j<m;j++) 
{ 
fontIptNum[j].className=""; 
if(j==num) fontIptNum[j].className="grea"; 
} 
}, 
getUrl:function() 
{ 
this.$("html").innerHTML=this.canvas.toDataURL(); 
}, 
resetEraser:function(_x,_y,touch) 
{ 
/*使用橡皮擦-提醒*/ 
var t=this; 
//this.cxt.lineWidth = 30; 
/*source-over 默认,相交部分由后绘制图形的填充(颜色,渐变,纹理)覆盖,全部浏览器通过*/ 
t.cxt.globalCompositeOperation = "destination-out"; 
t.cxt.beginPath(); 
t.cxt.arc(_x, _y, t.eraserRadius, 0, Math.PI * 2); 
t.cxt.strokeStyle = "rgba(250,250,250,0)"; 
t.cxt.fill(); 
t.cxt.globalCompositeOperation = "source-over" 
} 
}; 
paint.init(); 
})(); 
</script> 
<p style="clear:both"></p> 
</body> 
</html>

관련 기사:

순수한 CSS3 기반의 손으로 그린 ​​그래피티 버튼 효과 6개

사용 방법 CSS3를 적용한 html5로 Google 그래피티 애니메이션 완성

Html5는 그래피티 보드의 샘플 코드를 간단하게 구현

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

핫 AI 도구

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

HTML5 서버-미시록 이벤트로 다시 연결 및 오류를 처리합니다. HTML5 서버-미시록 이벤트로 다시 연결 및 오류를 처리합니다. Jul 03, 2025 am 02:28 AM

HTML5SSE를 사용하는 경우 재 연결 및 오류를 처리하는 방법에는 다음이 포함됩니다. 1. 기본 재 연결 메커니즘을 이해하십시오. 이벤트 소스는 기본적으로 연결이 중단 된 후 3 초 후에 재 시도합니다. 레트리 필드를 통해 간격을 사용자 정의 할 수 있습니다. 2. 오류 이벤트를 듣고 연결 고장 또는 구문 분석 오류를 처리하고 오류 유형을 구별하고 자동 재 연결에 의존하는 네트워크 문제, 서버 오류 재 연결 지연 및 인증 실패 TOKEN과 같은 해당 논리를 실행합니다. 3. 연결을 수동으로 닫고 재건하고, 최대 리트리 시간 수를 설정하고, Navigator.online과 네트워크 상태를 결합하여 재판 전략을 최적화하는 등 재 연결 로직을 적극적으로 제어하십시오. 이러한 조치는 응용 프로그램 안정성과 사용자 경험을 향상시킬 수 있습니다.

HTML5에 소개 된 주요 기능은 무엇입니까? HTML5에 소개 된 주요 기능은 무엇입니까? Jun 19, 2025 pm 11:57 PM

html5intructeDkeyFeaturestHattransformedWebDevelopment.1. SemanticElementslike, and andAccessility, andaccessibility.2.nativeMultimediasupportViaandTagseliminatedRelianceonPlugins.3.enhancedFormControlSinCludingType = "이메일"andr

HTML5 입력 유형 : 접근성을 향상 시킵니까? HTML5 입력 유형 : 접근성을 향상 시킵니까? Jun 20, 2025 am 12:49 AM

예, HTML5INPUTTYPESIMPROVECSESIBITY를 제공합니다

CSS 및 JavaScript를 HTML5 구조와 효과적으로 통합합니다. CSS 및 JavaScript를 HTML5 구조와 효과적으로 통합합니다. Jul 12, 2025 am 03:01 AM

HTML5, CSS 및 JavaScript는 시맨틱 태그, 합리적인 로딩 순서 및 디커플링 설계와 효율적으로 결합되어야합니다. 1. SEO 및 장벽이없는 액세스에 도움이되는 구조적 선명도 및 유지 보수성 향상과 같은 HTML5 시맨틱 태그를 사용하십시오. 2. CSS를 배치하고 외부 파일을 사용하고 모듈별로 분리하여 인라인 스타일과 지연된로드 문제를 피하십시오. 3. JavaScript는 정면에 도입되는 것이 권장되며 DEFER 또는 ASYNC를 사용하여 차단 렌더링을 피하기 위해 비동기 적으로로드합니다. 4. 데이터 사이의 강력한 의존성을 줄이고 데이터 속성 및 클래스 이름 제어 상태를 통해 동작을 구동하며 통합 이름 지정 사양을 통해 협업 효율성을 향상시킵니다. 이러한 방법은 페이지 성능을 효과적으로 최적화하고 팀과 협력 할 수 있습니다.

JavaScript를 사용하여 HTML5 비디오 및 오디오 재생을 제어하는 ​​방법은 무엇입니까? JavaScript를 사용하여 HTML5 비디오 및 오디오 재생을 제어하는 ​​방법은 무엇입니까? Jun 24, 2025 am 12:38 AM

JavaScript를 사용하여 HTML5 비디오 및 오디오 재생을 제어하려면 다음 주요 작업을 마스터하여 기본 제어를 달성하십시오. 1. 시작 또는 일시 정지 재생은 .play () 및 .pause () 메소드를 통해 달성 할 수 있으며, 모바일 브라우저와 호환되도록 사용자 상호 작용을 통해 트리거하는 것이 좋습니다. 2. 볼륨을 제어하고 볼륨 속성을 통해 값을 0에서 1로 설정하고 음소거 속성을 true 또는 false로 설정하여 전환하십시오. 3. 특정 시간으로 이동하면 현재 시간 속성을 사용하여 직접 할당을 지원하거나 현재 시간을 늘리거나 감소시키고 오류 처리를 추가하는 것이 좋습니다. 4. Play, Pause, Ended 및 TimeUpdate와 같은 이벤트를 통해 재생 상태 변경을 듣습니다.

HTML5 Server-Sent Events (SSE)로 실시간 데이터를 수신합니다. HTML5 Server-Sent Events (SSE)로 실시간 데이터를 수신합니다. Jul 02, 2025 pm 04:46 PM

SSE (Server-Sentevents)는 HTML5에서 실시간 업데이트를 브라우저로 푸시하기 위해 제공하는 경량 솔루션입니다. 주식 시장, 알림 및 기타 시나리오에 적합한 긴 HTTP 연결을 통한 일방 통신 통신을 실현합니다. 이벤트 소스 인스턴스를 생성하고 다음을 사용할 때 메시지를 듣습니다. consteventSource = newEventSource ( '/stream'); eventSource.onMessage = function (event) {console.log ( '수신 메시지 :', event.data);}; 서버는 컨텐츠 유형을 텍스트/이벤트로 설정해야합니다

최신 페이지에 대한 올바른 HTML5 DocType를 선언합니다. 최신 페이지에 대한 올바른 HTML5 DocType를 선언합니다. Jul 03, 2025 am 02:35 AM

DocType는 HTML 표준 브라우저를 페이지를 구문 분석하는 데 사용하는 브라우저를 알려주는 문입니다. 최신 웹 페이지는 HTML 파일의 시작 부분에서만 작성하면됩니다. 이 기능은 브라우저가 이상한 모드가 아닌 표준 모드로 페이지를 렌더링하고 첫 번째 줄에 위치해야합니다. 글을 쓰는 올바른 방법은 하나 뿐이며 이전 버전이나 다른 변형을 사용하는 것이 좋습니다. Charset, Viewport 등과 같은 다른 기타는 부분적으로 배치해야합니다.

HTML5 문서를 구성하기위한 모범 사례는 무엇입니까? HTML5 문서를 구성하기위한 모범 사례는 무엇입니까? Jun 26, 2025 am 01:03 AM

표준화되고 명확한 HTML5 문서를 구축하려면 다음 모범 사례를 따라야합니다. 1. 표준 문서 유형 선언을 사용하십시오. 2. 3 개의 태그를 포함한 기본 골격을 구축하고 캐릭터 세트, 제목 및 스크립트 위치에주의를 기울이십시오. 3. 접근성 및 SEO를 향상시키기 위해 시맨틱 태그를 사용하십시오. 4. 제목 레벨을 합리적으로 중첩하여 구조가 명확하고 페이지 당 하나만 있는지 확인하십시오. 이 단계는 코드 품질, 협업 효율성 및 사용자 경험을 향상시키는 데 도움이됩니다.

See all articles