Explicación básica del lienzo.

Tabla de contenido

1. Los navegadores de versión baja no muestran el lienzo y dan un mensaje

2. Canvas es un elemento en línea. Si desea centrarlo, debe convertirlo en un elemento de bloque

3. Dibuja la línea

 4. Dibuja un rectángulo

5. Limpiar el lienzo

 6. Dibuja un círculo

7. Dibuja un arco


1. Los navegadores de versión baja no muestran el lienzo y dan un mensaje

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <!-- canvas在低版本中不兼容,需要提示用户 -->
    <canvas width="500px" height="500px">您的浏览器版本过低,请升级浏览器或者使用chrome打开!</canvas>
</body>
</html>

Si se puede mostrar el lienzo, no habrá mensaje de texto, y si no se muestra el lienzo, se mostrará el texto del mensaje.

2. Canvas es un elemento en línea. Si desea centrarlo, debe convertirlo en un elemento de bloque

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        canvas {
            display: block;
            margin: 0 auto;
            border: 1px solid #aaa;
        }
    </style>
</head>
<body>
    <!-- canvas在低版本中不兼容,需要提示用户 -->
    <canvas width="500px" height="500px">您的浏览器版本过低,请升级浏览器或者使用chrome打开!</canvas>
</body>
</html>

 Efecto:

3. Dibuja la línea

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        // 只能使用原生js操作canvas, jq不可以
        // 画一条线的步骤

        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");
        // (3)开始一条路径
        ctx.beginPath();
        // (4)确定起点
        ctx.moveTo(100, 100);
        // (5)确定结束点
        ctx.lineTo(400, 400);
        // 添加线宽和颜色  (这个必须在着色之前写)
        // 设置颜色
        ctx.strokeStyle = 'green'
        // 设置线宽
        ctx.lineWidth=5
        // (6)着色
        ctx.stroke();
        // (7)结束路径
        ctx.closePath();

    </script>
</body>
</html>

Efecto:

4. Dibuja una línea de puntos

 gramática:

ctx.setLineDash([虚线长度, 虚线间隔])
drawLine(起始点的x坐标, 起始点的y坐标, 终点的x坐标, 终点的y坐标, 虚线的颜色 )

4. Dibuja un rectángulo

rect(x, y, width, height)  // 可描边、填充
fillRect(x, y, width, height)  // 不可描边、只能填充
strokeRect(x, y, width, height)  // 只能描边、不可填充
X La coordenada x de la esquina superior izquierda del rectángulo
y La coordenada y de la esquina superior izquierda del rectángulo
ancho El ancho del rectángulo, en píxeles
altura la altura del rectángulo en píxeles

Nota:  tenga en cuenta que primero debe rellenar y trazar   y luego trazar   , de lo contrario, el relleno presionará el trazo

caso:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");



        /**
         * rect(x, y, width, height) // 有描边也有填充
        */
        ctx.rect(100, 100, 300, 200)
        // 填充 
        ctx.fillStyle = "red"
        ctx.fill();
        // 描边
        ctx.strokeStyle = 'blue'
        ctx.lineWidth=5
        ctx.stroke();

        /**
         * fillRect(x, y, width, heihgt)  // 只能填充, 不可描边
        */
        ctx.fillStyle = 'pink'
        ctx.fillRect(100, 400, 100, 1000)

        /**
         * strokeRect(x, y, width, heihgt)
        */
        ctx.strokeStyle= 'gold'
        ctx.strokeRect(300, 400, 100, 100)


        ctx.closePath();
    </script>
</body>
</html>

 Efecto:

5. Limpiar el lienzo

gramática:

clearRect(x, y, width, height)

caso:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");


        ctx.rect(100, 100, 300, 200)
        // 填充 
        ctx.fillStyle = "red"
        ctx.fill();
        // 描边
        ctx.strokeStyle = 'blue'
        ctx.lineWidth=5
        ctx.stroke();
        
        // 清除画布
        ctx.clearRect(120, 120,200, 100)
        
        ctx.closePath();
    </script>
</body>
</html>

Efecto:

 6. Dibuja un círculo

gramática:

arc(x, y, radius, startAngle, endAngle, counterclockwise)

parámetro

X Centro x coordenada
y Centro y coordenada
radio radio
ángulo inicial ángulo inicial
ángulo final ángulo final
en sentido anti-horario verdadero: en el sentido contrario a las agujas del reloj, falso: en el sentido de las agujas del reloj

caso:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");


        ctx.arc(250, 250, 200, 0, Math.PI*2, false)
        ctx.fillStyle = 'gold'
        ctx.fill()
        
        ctx.lineWidth = 10;
        ctx.strokeStyle = 'red'
        ctx.stroke()
        
        ctx.closePath();
    </script>
</body>
</html>

Efecto:

7. Dibuja un arco

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");

        ctx.beginPath()
        ctx.arc(100, 100, 100, 0, Math.PI*1, true)
        ctx.stroke()

        ctx.beginPath()  // 当前使用了新了一个beginPath()   所以上一个不需要closePath   因为他默认给你加上了
        ctx.arc(300, 100, 100, 0, Math.PI*1, false)
        ctx.stroke()
        
        ctx.closePath();
    </script>
</body>
</html>

Nota:  actualmente se usa un nuevo beginPath(), por lo que el anterior no necesita closePath porque él lo agregó de manera predeterminada

Ocho, haz dibujos

método uno

// 在画布上定位图像
ctx.drawImage(img, x, y)

 forma dos

// 在画布上定位图像  并规定图像的宽、高
ctx.drawImage(img, x, y, width, height)

forma tres

// 剪切图像,并在画布上定位被裁剪的部分
ctx.drawImage(img, sx, sy, swidth, sheight, x, y, width, height)

 parámetro:

imagen Imagen, lienzo, video para usar
sx opcional. coordenada x para comenzar a recortar
y opcional. La coordenada y en la que comenzar a recortar
ancho opcional. El ancho de la imagen recortada
altura opcional. La altura de la imagen recortada
X coordenada x para colocar la imagen en el lienzo
y La coordenada y para colocar la imagen en el lienzo.
ancho opcional. El ancho de la imagen a usar. (estirar o encoger la imagen)
altura opcional. La altura de la imagen a utilizar. (estirar o encoger la imagen)

8. Caso: Detección de golpe de bola pequeña contra la pared

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");
        // 画布宽高
        var w=h=500;
        var x = 100;
        var y = 100;
        var r = 30;

        // 水平速度
        var xSpeed = 10;
        // 垂直运动
        var ySpeed = 6;

        setInterval(function() {
            // 每次都要清除整个画布
            ctx.clearRect(0, 0, w, h);

            // 在小球碰到边缘时,速度取相反即可
            if(x-r <= 0 || x+r > w ) {
                xSpeed = -xSpeed;
            }
            x = x+xSpeed

            if(y-r <= 0 || y+r > w ) {
                ySpeed = -ySpeed;
            }
            y = y+ySpeed
            
            // 水平运动
            drawCircle(x, y, r);
        }, 50)

        function drawCircle(x, y, r) {
            // 加这个相当于把上面一次的画笔清除掉  否则就相当于你的笔重来都没有离开过画布
            ctx.beginPath()
            ctx.arc(x, y, r, 0, Math.PI*2);
            ctx.fillStyle = 'gold'
            ctx.fill()
        }
    </script>
</body>
</html>

Efecto: Rebotará cuando golpee el entorno.

 9. Caso: Detección de bola pequeña golpea la pared (orientada a objetos)

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        //(1)获取画布
        var canvas = document.querySelector("#cont");
        //(2)获取画布的能力
        var ctx = canvas.getContext("2d");
        // 画布宽高
        var w = 500
        var h = 500
        var ballArr = []

        /**
         * 面向对象
         * 
        */
        function r(num) {
            return Math.random()*num
        }
        /**
         * @param x       起始x坐标
         * @param y       起始y坐标
         * @param r       小球半径
         * @param color   小球颜色
         * @param xSpeed  x轴速度
         * @param ySpeed  y轴速度
         * @author: @郑建
         */        
        function Ball() {
            this.x = r(5) + 60;
            this.y = r(3) + 60;
            this.r = r(50) + 10 // [10, 100)
            this.color = '#' + parseInt(Math.random()*0xffffff).toString(16)

            this.xSpeed = r(3) + 2;  // [2, 5)
            this.ySpeed = r(3) + 1;  // [1, 4)
        }

        // 在原型链上定义小球的公共方法
        Ball.prototype.show = function() {
            this.run()
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, 0, Math.PI*2);
            ctx.fillStyle = this.color
            ctx.fill();
        }
        // 在原型链上定义小球的公共方法
        Ball.prototype.run = function() {
            if(this.x-this.r <= 0 || this.x+this.r >= w) {
                this.xSpeed = -this.xSpeed
            }
            this.x = this.x + this.xSpeed

            if(this.y-this.r <= 0 || this.y+this.r >= w) {
                this.ySpeed = -this.ySpeed
            }
            this.y = this.y + this.ySpeed

        }

        
        for(var i = 0; i < 1000; i++) {
            var ball = new Ball()
            ballArr.push(ball)
            ball.show()
        }

        setInterval(function() {
            ctx.clearRect(0, 0, w, h)
            for(var i = 0; i < ballArr.length; i++) {
                var ball = ballArr[i]
                ball.show()
            }
        }, 20)
    </script>
</body>
</html>

 Efecto:

Diez, pictografías

1. Pantalla básica

gramática:

fillText(text, x, y, maxWidth);  // 实心文字
strokeText(text, x, y, maxWidth);  // 空心文字

parámetro:

texto Salida de texto en el lienzo
X La posición de la coordenada x en la que empezar a dibujar el texto
y La posición de la coordenada y en la que empezar a dibujar el texto
anchura máxima opcional. el ancho de texto máximo permitido,

Caso número uno:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        var canvas = document.querySelector("#cont");
        var ctx = canvas.getContext("2d");

        
        // 1.设置字体样式
        // font
        ctx.font = '30px 微软雅黑';
        //字体颜色
        ctx.fillStyle = 'gold'
        // 2.画文字
        ctx.fillText('实心文字', 250, 250)

        //  空心文字
        ctx.strokeStyle = 'red'
        ctx.strokeText('空心文字', 0, 250)

        //  未设置最大宽度
        ctx.fillStyle = 'red'
        ctx.fillText('你好!我是未设置最大宽度的字体', 100, 50)
        //  设置最大宽度
        ctx.fillStyle = 'green'
        ctx.fillText('你好!我设置最大宽度的字体', 100, 100, 300)
        
    </script>
</body>
</html>

Efecto:

2. Gradiente de texto

gramática:

var gradient = ctx.createLinearGradient(x0, y0, x1, y1)

 parámetro:

x0 La coordenada x del punto de inicio del gradiente
y0 La coordenada y del punto de inicio del gradiente
x1 La coordenada x del punto final del gradiente.
y1 La coordenada y del punto final del gradiente.

caso:

<!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>Document</title>
    <style>
        canvas {
            display: block;
            margin: 0 auto;
            border: 1px solid #aaa;
        }
    </style> 
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        var canvas = document.querySelector("#cont");
        var ctx = canvas.getContext("2d");

        
        ctx.font = '50px 微软雅黑';
        /**
         * 设置线性渐变
        */
        var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0)
        gradient.addColorStop('0', "yellow")
        gradient.addColorStop('0.5', 'blue')
        gradient.addColorStop('1.0', 'red')

        
        ctx.fillStyle = gradient
        ctx.fillText('今天天气不错, 风和日丽!', 0, 100, 500)
        ctx.strokeStyle = gradient
        ctx.strokeText('适合出去玩儿!happy~', 0, 300, 500)
        
    </script>
</body>
</html>

 Efecto:

 3. Posición del texto

gramática:

textAlign = 'start' | 'end' | 'left' | 'right' | 'center'   // 水平方向
textBaseLine = 'top' | 'bottom' | 'moddle' | 'alphabetic' | 'hanging'

píxel

gramática: 

ctx.getImageData(x, y, width, height)

parámetro:

X La coordenada x de la ubicación de la esquina superior izquierda para comenzar a copiar
y La coordenada y de la posición de la esquina superior izquierda para comenzar a copiar
ancho El ancho del área rectangular que se va a copiar.
altura 将要复制的矩形区域的高度

介绍:

返回的getImageData对象,该对象拷贝了画布指定矩形的像素数据

对于getImageData对象中的每个像素,都存在着四方面的信息, 即RGBA值

R - 红色 (0 - 255)  

G - 绿色 (0 - 255)  

B - 蓝色 (0 - 255)  

A - alpha 通道 (0 - 255) ; 0: 透明; 255:完全不透明

color / alpha 以数组的形式存在,并存储于getImage对象的data属性中   

案例:

<!DOCTYPE html>
<html lang="en">
<head> 
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        var canvas = document.querySelector("#cont");
        var ctx = canvas.getContext("2d");
        // 1 创建图片
        var img = new Image();
        img.src = 'u10.png'
        img.onload = function() {
            // 2 绘制图片
            ctx.drawImage(img, 0, 0, img.width, img.height)
            // 3 获取像素点
            var copy = ctx.getImageData(0, 0, 10, 10);
            console.log('像素数据', copy);
        }
    </script>
</body>
</html>

打印:

 

把像素点放到画布上

语法:

putImageData(imgData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight)

参数:

imgData 规定要放回画布的ImageData对象
x ImageData对象左上角的 x 坐标,以像素计
ImageData对象左上角的 y 坐标,以像素计
dirtyX 可选。 水平值(x), 在画布上放置图片的位置
dirtyY 可选。 水平值(y), 在画布上放置图片的位置
dirtyWidth 可选。 在画布上绘制图像所使用的宽度
dirtyHeight 可选。 在画布上绘制图像所使用的高度

案例:

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
    <canvas id="cont" width="500px" height="500px"></canvas>
    <script>
        var canvas = document.querySelector("#cont");
        var ctx = canvas.getContext("2d");
        // 1 创建图片
        var img = new Image();
        img.src = 'u10.png'
        img.onload = function() {
            // 2 绘制图片
            ctx.drawImage(img, 0, 0, 250, 250)
            // 3 获取像素点
            var copy1 = ctx.getImageData(0, 0, 100, 100);
            
            ctx.putImageData(copy1, 0, 350)
        }
    </script>
</body>
</html>

效果:

 

Supongo que te gusta

Origin blog.csdn.net/qq_52421092/article/details/130009271
Recomendado
Clasificación