文本缩放并旋转
源码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文本缩放并旋转</title> <style> #canvas { -webkit-box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 4px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 4px; box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 4px; border: 1px solid cornflowerblue; background: aqua; } </style> </head> <body> <canvas id="canvas" width="600" height="420"> Canvas not supported </canvas> </body> <script> 'use strict'; let canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), text = '触发旋转', angle = Math.PI / 50, //顺时针方向 clockwise = true, fontHeight = 128, origin = {}, paused = true, scale = 1.008; //Function…… //画字 let drawText = () => { context.fillText(text, 0, 0); context.strokeText(text, 0, 0); }; //Event handlers…… canvas.onclick = () => { paused = !paused; //当启动当时候 if (!paused) { //调换旋转方向 clockwise = !clockwise; //减小缩放尺寸 scale = 1 / scale; } }; //Animation…… setInterval(() => { if (!paused) { //清楚缩放后的画布 context.clearRect(-origin.x, -origin.y, canvas.width, canvas.height); //以angle角度旋转画布 context.rotate(clockwise ? angle : -angle); //以scale比例缩放画布 context.scale(scale,scale); drawText(); } }, 1000 / 60); //Init…… context.font = fontHeight + 'px Palatino'; context.fillStyle = 'cornflowerblue'; context.strokeStyle = 'yellow'; context.shadowColor = 'rgba(100, 100, 150, 0.8)'; context.shadowOffsetX = 5; context.shadowOffsetY = 5; context.shadowBlur = 10; context.textAlign = 'center'; context.textBaseline = 'middle'; origin.x=canvas.width/2; origin.y=canvas.height/2; //将坐标轴平移到中心位置 context.transform(1,0,0,1,origin.x,origin.y); drawText(); </script> </html>