zoukankan      html  css  js  c++  java
  • 12 canvas 画布

    二、线条的绘制和填充

    在canvas中,各个图像绘制代码可以通过beginPath()和closePath()这两个函数进行包裹,主要用于分割各个画图,表示开始和结束。线条的绘制主要调用方法是moveTo(x,y)、lineTo(x,y)、stroke()、arc()、arcTo()、fill(),使用的属性包括lineWidth、lineCap、lineJoin、strokeStyle、fillStyle等。

    1、画出边角为圆角的一条线段

    复制代码
    ctx.beginPath();
    ctx.strokeStyle = "black";
    ctx.lineWidth = 6;
    ctx.lineCap = "round";
    ctx.moveTo(400,400);
    ctx.lineTo(600,400);
    ctx.stroke();
    ctx.closePath();
    复制代码

    效果图为:

    其中strokeStyle表示线条的颜色,lineWidth表示线条的宽度,lineCap设置线条的边缘为圆角,lineCap的属性有butt|round|square,第一个是默认值表示平直的边缘,round为圆角,square为正方的边缘。moveTo(x,y)表示划线的起点为(x,y)坐标,而lineTo(x,y)设置线条的终点为(x,y),最后通过调用stroke()方法进行绘制。

    2、画出两条线段,焦点为圆角

    复制代码
    ctx.beginPath();
    ctx.strokeStyle = "black";
    ctx.lineWidth = 10;
    ctx.lineJoin = "round";
    ctx.moveTo(400,500);
    ctx.lineTo(600,500);
    ctx.lineTo(600,600);
    ctx.stroke();
    ctx.closePath();
    复制代码

    效果图为:

    和上面的demo的不同点在于使用的属性为lineJoin,同样它也有三个属性bevel|round|miter,第一个是默认值表示斜角,而miter表示尖角。同时lineTo(x,y)可以调用多次,进行线段的绘制,所以可以通过moveTo()和lineTo()这两个方法进行多边形的绘制

    3、矩形的绘制并填充颜色

    复制代码
    ctx.beginPath();        
    ctx.moveTo(50,50);
    ctx.lineTo(100,50);
    ctx.lineTo(100,100);
    ctx.lineTo(50,100);
    ctx.lineTo(50,50);
    ctx.lineWidth = 4;
    ctx.strokeStyle = "red";
    ctx.stroke();
    ctx.fillStyle = "blue";
    ctx.fill();
    ctx.closePath();
    复制代码

    效果图为:

    通过moveTo()和lineTo()方法进行多边形的绘制后,得到了一个闭合区间,就可以调用fill()方法对其中的颜色进行填充,fillStyle则是设置闭合区间内的颜色。如果不用stroke()方法,也就是不绘制外边框的线条,则可以省去最后的那个回到起点的方法ctx.lineTo(50,50),因为fill()会自动将起点和终点进行连接得到一个闭合区间。

    如果是单纯的矩形而非不规则的多变型的时候,可以直接调用canvas的api方法strokeRect(x,y,w,h)和fillRect(x,y,w,h);前两个参数表示起点的坐标,后两个表示矩形的宽度和高度。

    复制代码
    ctx.beginPath();
    ctx.lineWidth = 3;
    ctx.strokeStyle = "darkgray";
    ctx.strokeRect(50,50,200,100);
    ctx.closePath();
    
    ctx.beginPath();
    ctx.fillStyle = "coral";
    ctx.fillRect(300,50,200,100);
    ctx.closePath();
    复制代码

    效果图为:

  • 相关阅读:
    53. Maximum Subarray
    64. Minimum Path Sum
    28. Implement strStr()
    26. Remove Duplicates from Sorted Array
    21. Merge Two Sorted Lists
    14. Longest Common Prefix
    7. Reverse Integer
    412. Fizz Buzz
    linux_修改域名(centos)
    linux_redis常用数据类型操作
  • 原文地址:https://www.cnblogs.com/langwo/p/7581441.html
Copyright © 2011-2022 走看看