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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| <!DOCTYPE html> <html>
<head> <title>渲染效果(gradient)</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="800" height="480" style="border:solid 1px #CCCCCC;"></canvas> </body> <script> let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); let size = 100;
let image = new Image(); image.onload = function () { draw(); } image.src = "/examples/canvas-qa/canvas_1b/images/wood2.png";
function draw() { let pattern = ctx.createPattern(image, "repeat"); ctx.save(); ctx.fillStyle = pattern; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.restore();
drawGrid('lightgray', 10, 10);
drawBoards();
drawPiece(2, 1, 1); drawPiece(3, 0, 1); drawPiece(3, 1, 1); drawPiece(2, 1, 1); drawPiece(0, 2, 1); drawPiece(1, 2, 1); drawPiece(2, 2, 1); drawPiece(3, 2, 0); drawPiece(4, 0, 0); drawPiece(4, 1, 0); drawPiece(0, 3, 0); drawPiece(1, 3, 0); drawPiece(2, 3, 0); drawPiece(3, 3, 0); }
function drawBoards() { ctx.save(); ctx.beginPath(); ctx.lineCap = "square"; for (let i = size; i < canvas.width; i += size) { ctx.moveTo(i, size); ctx.lineTo(i, canvas.height) } for (let i = size; i < canvas.width; i += size) { ctx.moveTo(size, i); ctx.lineTo(canvas.width, i) } ctx.lineWidth = 6; ctx.stroke(); ctx.restore(); }
function drawPiece(x, y, type) { x = (x + 1) * 100; y = (y + 1) * 100; let radius = size/2 - 2;
const gradient = ctx.createRadialGradient(x + radius / 2, y - radius / 2, 0, x, y, radius); gradient.addColorStop(0, type == 1 ? "#B9B9B9" : "#FFFFFF"); gradient.addColorStop(0.95, type == 1 ? "#000000" : "#DCDCDC"); gradient.addColorStop(0.97, type == 1 ? "#000000" : "#DCDCDC00"); gradient.addColorStop(1, type == 1 ? "#00000000" : "#DCDCDC00");
ctx.save(); ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.fillStyle = gradient; ctx.fill(); ctx.restore(); } </script>
</html>
|