canvas-文字样式-文字水平垂直居中

  • Post author:
  • Post category:其他


<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8″>

<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>

<title>文本水平垂直居中</title>

<style>

body,  html {

background-color: #bfa;

overflow: hidden;

}

canvas {

margin: 150px auto;

border: 1px solid black;

display: block;

background-color: white;

}

</style>

</head>

<body>

<canvas id=”test” width=”300″ height=”300″>

<span>您的浏览器版本过低,请更换IE-9以上,或使用chrome等其他浏览器</span>

</canvas>

<script type=”text/javascript”>

window.onload = function(){

/** @type {HTMLCanvasElement} */

//1.获取画布

var canvas = document.querySelector(‘#test’);

if (canvas.getContext) {

//2.获取画笔

var ctx = canvas.getContext(‘2d’);

ctx.font = ’60px impact’;

ctx.textBaseline = ‘middle’;

var measure = ctx.measureText(‘测试’).width;

ctx.fillText(‘测试’,(canvas.width-measure)/2,(canvas.height-60)/2);

}

}

</script>

</body>

</html>



版权声明:本文为weixin_54057363原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。