canvas_09 像素文字

2021/12/27 6:08:56

本文主要是介绍canvas_09 像素文字,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

效果图:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <meta http-equiv="X-UA-Compatible" content="IE=edge">
 6         <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7         <title>Canvas</title>
 8         <style>
 9             canvas {
10                 margin: 0 auto;
11                 border: 1px solid #aaa;
12                 display: block;
13             }
14         </style>
15     </head>
16     <body>
17         <canvas width="500px" height="500px" id="canvas"></canvas>
18 
19         <script>
20             var canvas = document.querySelector("#canvas");
21             var ctx = canvas.getContext("2d");
22 
23             /*
24                 ctx.getImageData(x, y, width, height) 返回数组
25                 R - 红色 (0 - 255)
26                 G - 绿色 (0 - 255)
27                 B - 蓝色 (0 - 255)
28                 A - alpha (0 - 255)   0 透明,255不透明
29                 
30                 var img = new Image();
31                 img.src = "./1.jpeg";
32                 img.onload = () => {
33                     ctx.drawImage(img, 0, 0, 200, 200);
34                     var copy = ctx.getImageData(40, 20, 50, 50);
35                     ctx.putImageData(copy, 0, 300);
36                 };
37             */
38 
39             var w = canvas.width;
40             var h = canvas.height;
41 
42             function drawCircle(x, y, r, color) {
43                 ctx.beginPath();
44                 ctx.arc(x, y, r, 0, Math.PI * 2);
45                 ctx.fillStyle = color || "#000";
46                 ctx.fill();
47             }
48 
49             function drawText(text, x, y) {
50                 ctx.font = "300px 微软雅黑";
51                 ctx.textAlign = "center";
52                 ctx.textBaseline = "middle";
53                 ctx.fillText(text, x, y, w);
54             }
55 
56             // step_01 画文字
57             drawText("❤", w / 2, h / 2);
58 
59             // step_02 获取像素点
60             var copy = ctx.getImageData(0, 0, w, h);
61 
62             // step_03 清除画布
63             ctx.clearRect(0, 0, w, h);
64 
65             // step_04 筛选有效像素点
66             var leap = 3;
67             for (var y = 0; y < h; y += leap) {
68                 for (var x = 0; x < w; x += leap) {
69                     var index = x + y * w; // 公式
70                     var a = copy.data[index * 4 + 3];
71                     if (a > 128) {
72                         // step_05 画圆
73                         drawCircle(x, y, 1, "#f00")
74                     }
75                 }
76             }
77         </script>
78     </body>
79 
80 </html>

 



这篇关于canvas_09 像素文字的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程