Last active
September 20, 2018 00:53
-
-
Save khrtz/55d0417a4ea7bdaed0e961723142bd57 to your computer and use it in GitHub Desktop.
文字列をCanvasで描画
This file contains 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> | |
<head> | |
<title>canvas test</title> | |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> | |
<style type="text/css"> | |
body { | |
font-size: 100px; | |
} | |
.canvas { | |
height: 120px; | |
} | |
canvas { | |
/* image-rendering: pixelated; */ | |
image-rendering: crisp-edges; | |
-webkit-font-smoothing: antialiased; | |
-moz-osx-font-smoothing: antialiased; | |
background-color: #000; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="canvas">あいうABC123][';/,@%$#</div> | |
<script type="text/javascript"> | |
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', { | |
alpha: true, | |
depth: false, | |
antialias: true | |
}), | |
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 = '#fff'; | |
tmpCanvas.fillText(text, 20, 20); | |
// tmpCanvas.lineJoin = 'miter'; | |
// tmpCanvas.miterLimit = 1; | |
// tmpCanvas.stroke(); | |
// tmpCanvas.restore(); | |
console.log('tmpCanvas', tmpCanvas); | |
canvas.drawImage(tmpElement, 0, 0, textWidth, fontSize, x, y, textWidth/ratio, fontSize/ratio); | |
$tmpElement.remove(); | |
}; | |
$('.canvas').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