実験室

一定幅に表示された文字数を取得する。

PrototypeのgetStyle()は厳密ではないため、getComputedStyle()を使用。

document.defaultView.getComputedStyle()の方がいいのか、window.getComputedStyleでいいのか、それぞれの特徴を理解できていないため、とりあえずwindow.getComputedStyle()を使用。

CANVAS必須。currentStyleは一応書いてあるが、IEでの動作検証はしていない。

widthを%やptなど、px以外の単位で指定した場合の動作は未検証。

コード


// use Prototype
	var canvas=new Element('canvas');
	var ctx=canvas.getContext('2d');
	
	function initialize(){
		$('get_size1').on('click', getSize);
		$('get_size2').on('click', getSize);
	}
	
	function getSize(e){
		id='the_text'+e.target.id.slice(-1);
		var p=$(id);

		var p=$(id);
		var fonts=[];
			fonts[0]=getStyle(p,'fontStyle');
			fonts[1]=getStyle(p,'fontVariant');
			fonts[2]=getStyle(p,'fontWeight');
			fonts[3]=getStyle(p,'fontSize')+'/'+getStyle(p,'lineHeight');
			fonts[4]=getStyle(p,'fontFamily');
		ctx.font=fonts.join(' ');
//		fontStretch=getStyle(p,'fontStretch'); // not supported (?)
//		ctx.font=getStyle(p,'font'); // does not work

		var htmlWidth=parseInt(getStyle(p,'width'));
		var text=p.textContent;
		
		var result=0;
		for(var i=1,t;i<=text.length;i++){
			t=text.substr(0,i);
			if( ctx.measureText(t).width>htmlWidth ){
				break;
			}else{
				result++;
			}
		}
	
		$('output').value=htmlWidth+'px '+result+'文字';
		
	}
	
	
	function getStyle(element, style) {
	//	return element.getStyle(style);
		
		if( window.getComputedStyle ){
			var styleObj = window.getComputedStyle(element, null);
			return styleObj[style];
		}else{
			return element.currentStyle[style];
		}
	}
	
	Event.on(window, 'load', initialize);

1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890

1234567890123456789012345678901234567890

12345678901234567890123456789012345678901234567890

comments powered by Disqus

© Wicker Wings, 2004-2012

BACK