用 canvas 原生JS创建红色公章

function officialseal(opt) {
	opt = opt || {
		canvas: $$('#canvas'),
		companyName: canvas.getAttribute('data-companyName'),
		sealTypeName: canvas.getAttribute('data-sealTypeName')
	};
	
	// official seal
	var ctx = opt['canvas'].getContext('2d'), color = '#f00', width = opt['canvas'].width/2, height = opt['canvas'].height/2;
	ctx.lineWidth = 6;
	ctx.strokeStyle = color;
	ctx.beginPath();
	ctx.arc(width, height, 110, 0, Math.PI*2);
	ctx.stroke();

	// five pointed star
	var radius = 30, rotato = 0;
	ctx.save();
	ctx.fillStyle = color;
	ctx.translate(width, height);
	ctx.rotate(Math.PI+rotato);
	ctx.beginPath();
	var x, y, dig = Math.PI/5*4;
	for (var i = 0;i< 5;i++) {
		 x = Math.sin(i*dig);
		 y = Math.cos(i*dig);
		 ctx.lineTo(x*radius, y*radius);
	}
	ctx.closePath();
	ctx.stroke();
	ctx.fill();
	ctx.restore();
	
	// sealTypeName
	ctx.font = '20px Microsoft YaHei';
	ctx.textBaseline = 'middle';
	ctx.textAlign = 'center';
	ctx.lineWidth = 1;
	ctx.fillStyle = color;
	ctx.fillText(opt['sealTypeName'], width, height+70);

	// companyName
	ctx.translate(width, height);
	ctx.font = '26px Microsoft YaHei';
	var  chars = opt['companyName'].split('')
		, count = chars.length
		, angle = 4*Math.PI / (3*(count - 1))
	;
	for (var i = 0; i < chars.length; i++){ // var character = chars[i];
		if (i == 0) {
			ctx.rotate(5*Math.PI/6);
		} else {
			ctx.rotate(angle);
		}
		ctx.save(); 
		ctx.translate(90, 0);
		ctx.rotate(Math.PI/2);
		ctx.fillText(chars[i], 0, 5);
		ctx.restore(); 
	}
}







official_seal






用 canvas 原生JS创建红色公章_第1张图片

你可能感兴趣的:(javascript,html)