Last active
January 7, 2017 13:53
-
-
Save comilab/6327091 to your computer and use it in GitHub Desktop.
canvas要素を使って文字を綺麗に描画してみる
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="utf-8"> | |
<title></title> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> | |
<style type="text/css"> | |
body { | |
font-size: 22px; | |
} | |
</style> | |
</head> | |
<body> | |
<div>新しい朝が来た希望の朝だ</div> | |
<div class="beautify">新しい朝が来た希望の朝だ</div> | |
<script type="text/javascript"> | |
$(function() { | |
var drawText = function(canvas, x, y, text, fontSize, fontFamily) { | |
var ratio = 2, | |
fontSize = fontSize * ratio, | |
$tmpElement = $('<canvas></canvas>').attr('height', fontSize), | |
tmpElement = $tmpElement.get(0), | |
tmpCanvas = tmpElement.getContext('2d'), | |
font = fontSize + 'px ' + fontFamily, | |
textWidth; | |
tmpCanvas.font = font; | |
textWidth = tmpCanvas.measureText(text).width; | |
$tmpElement.attr('width', textWidth); | |
tmpCanvas.font = font; | |
tmpCanvas.textBaseline = 'top'; | |
tmpCanvas.fillStyle = '#000'; | |
tmpCanvas.fillText(text, 0, 0); | |
canvas.drawImage(tmpElement, 0, 0, textWidth, fontSize, x, y, textWidth/ratio, fontSize/ratio); | |
$tmpElement.remove(); | |
}; | |
$('.beautify').each(function() { | |
var $this = $(this), | |
$canvas = $('<canvas></canvas>').attr('width', $this.width()).attr('height', $this.height()), | |
context = $canvas.get(0).getContext('2d'), | |
fontSize = $this.css('font-size').replace('px', ''); | |
drawText(context, 0, 0, $this.text(), fontSize, $this.css('font-family')); | |
$this.html($canvas); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment