1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| <!DOCTYPE html> <html>
<head> <title>变形操作(setTransform)</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="图形系统开发实战:基础篇 示例"> <meta name="author" content="hjq"> <meta name="keywords" content="canvas,ladder,javascript"> <script src="/examples/canvas-qa/canvas_1b/js/helper.js"></script> </head>
<body style="overflow: hidden; margin:10px;"> <canvas id="canvas" width="600" height="450" style="border:solid 1px #CCCCCC;"></canvas> </body> <script> let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); drawGrid('lightgray', 10, 10); ctx.lineWidth = 4;
drawRect1(100, 200, 400, 60, 0); drawRect1(100, 200, 400, 60, 30); drawRect1(100, 200, 400, 60, 60);
drawRect2(100, 200, 400, 60, 90); drawRect2(100, 200, 400, 60, 120); drawRect2(100, 200, 400, 60, 150);
function drawRect1(x, y, width, height, angle) { ctx.save(); ctx.translate(x + width / 2, y + height / 2); ctx.rotate(angle * Math.PI / 180); ctx.translate(-(x + width / 2), -(y + height / 2)); ctx.strokeStyle = "blue"; ctx.strokeRect(x, y, width, height); ctx.restore(); }
function drawRect2(x, y, width, height, angle) { ctx.save(); let sin = Math.sin(angle * Math.PI / 180); let cos = Math.cos(angle * Math.PI / 180); ctx.transform(1, 0, 0, 1, x + width / 2, y + height / 2); ctx.transform(cos, sin, -sin, cos, 0, 0); ctx.transform(1, 0, 0, 1, -(x + width / 2), -(y + height / 2)); ctx.strokeStyle = "red"; ctx.strokeRect(x, y, width, height); ctx.restore(); } </script>
</html>
|