>  기사  >  웹 프론트엔드  >  HTML5 Canvas 사용자 정의 둥근 사각형 및 점선 코드 예제 소개

HTML5 Canvas 사용자 정의 둥근 사각형 및 점선 코드 예제 소개

黄舟
黄舟원래의
2017-03-03 15:58:272918검색

HTML5 Canvas 사용자 정의 둥근 직사각형 및 점선(RoundedRectangle 및 Dash Line)

HTML Canvas 2d 컨텍스트 그리기 객체에 사용자 정의 기능을 추가하는 방법에 대한 데모를 구현합니다. 점선 그리기

점선 간격의 크기를 조절하고, 둥근 사각형을 그리는 기술을 배워보세요.

HTML5 Canvas 그리기 개체에서 제공하는 기본 기능은 둥근 사각형과 점선을 그리는 기능을 구현하지 않지만

JavaScript 언어 .prototype의 개체는 이 두 기능을 CanvasRenderingContext2D 개체에 추가할 수 있습니다. 코드의 시연 효과는 다음과 같습니다.

컴포넌트의 코드 fishcomComponent.js는 다음과 같습니다:

CanvasRenderingContext2D.prototype.roundRect =
	function(x, y, width, height, radius, fill, stroke) {
		if (typeof stroke == "undefined") {
			stroke = true;
		}
		if (typeof radius === "undefined") {
			radius = 5;
		}
		this.beginPath();
		this.moveTo(x + radius, y);
		this.lineTo(x + width - radius, y);
		this.quadraticCurveTo(x + width, y, x + width, y + radius);
		this.lineTo(x + width, y + height - radius);
		this.quadraticCurveTo(x + width, y + height, x + width - radius, y+ height);
		this.lineTo(x + radius, y + height);
		this.quadraticCurveTo(x, y + height, x, y + height - radius);
		this.lineTo(x, y + radius);
		this.quadraticCurveTo(x, y, x + radius, y);
		this.closePath();
		if (stroke) {
			this.stroke();
		}
		if (fill) {
			this.fill();
		}
};

CanvasRenderingContext2D.prototype.dashedLineTo = function (fromX, fromY, toX, toY, pattern) {
	// default interval distance -> 5px
	if (typeof pattern === "undefined") {
		pattern = 5;
	}

	// calculate the delta x and delta y
	var dx = (toX - fromX);
	var dy = (toY - fromY);
	var distance = Math.floor(Math.sqrt(dx*dx + dy*dy));
	var dashlineInteveral = (pattern <= 0) ? distance : (distance/pattern);
	var deltay = (dy/distance) * pattern;
	var deltax = (dx/distance) * pattern;
	
	// draw dash line
	this.beginPath();
	for(var dl=0; dl<dashlineInteveral; dl++) {
		if(dl%2) {
			this.lineTo(fromX + dl*deltax, fromY + dl*deltay);
		} else {    				
			this.moveTo(fromX + dl*deltax, fromY + dl*deltay);    				
		}    			
	}
	this.stroke();
};

HTML에서 호출하는 데모:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="chrome=IE8">
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Canvas Rounded Rectangle Demo</title>
<script src="fishcomponent.js"></script>
<link href="default.css" rel="stylesheet" />
	<script>
		var ctx = null; // global variable 2d context
		var imageTexture = null;
		window.onload = function() {
			var canvas = document.getElementById("text_canvas");
			console.log(canvas.parentNode.clientWidth);
			canvas.width = canvas.parentNode.clientWidth;
			canvas.height = canvas.parentNode.clientHeight;
			
			if (!canvas.getContext) {
			    console.log("Canvas not supported. Please install a HTML5 compatible browser.");
			    return;
			}
			var context = canvas.getContext(&#39;2d&#39;);
			context.strokeStyle="red";
			context.fillStyle="RGBA(100,255,100, 0.5)";
			context.roundRect(50, 50, 150, 150, 5, true);
			context.strokeStyle="blue";								
			for(var i=0; i<10; i++) {
				var delta = i*20;
				var pattern = i*2+1;
				context.dashedLineTo(250, 50+delta, 550, 50+delta, pattern);
			}
		}
	</script>
</head>
<body>
	<h1>HTML5 Canvas Dash-line Demo - By Gloomy Fish</h1>
	<pre class="brush:php;toolbar:false">Dash line and Rounded Rectangle

위는 HTML5 Canvas 사용자 정의 둥근 사각형과 점선의 코드 예제 소개입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요!


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