HTML5 Canvas カスタムの角丸四角形と点線のコード例の紹介

黄舟
リリース: 2017-03-03 15:58:27
オリジナル
2917 人が閲覧しました

HTML5 Canvas カスタムの角丸四角形と破線 (RoundedRectangle と Dash Line)

は、HTML Canvas 2D コンテキスト描画オブジェクトにカスタム関数を追加するデモ、破線を描画する方法

と間隔を制御する方法を実装します。破線のサイズ、角丸長方形を描くテクニックを学びます。

HTML5のCanvas描画オブジェクトが提供するネイティブ関数には角丸四角形や点線を描画する機能は実装されていませんが、

はJavaScript言語CanvasRenderingContext2DaddのObject.prototypeを通じて実現可能です。

これら2つの関数を追加します。コードのデモの効果は次のとおりです:

コンポーネントfishcomponent.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でデモを呼び出します:

そうだね

以上 これは HTML5 Canvas カスタムの角丸四角形と点線のコード例の紹介です。その他の関連コンテンツについては、PHP 中国語 Web サイト (www.php.cn) に注目してください。


関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!