canvas 绘制图片形状_使用JavaScript Canvas API绘制形状

canvas 绘制图片形状

In this article we’ll be looking at the HTML canvas element and the JavaScript canvas API to render complex shapes onto our web pages.

在本文中,我们将研究HTML画布元素和JavaScript画布API,以将复杂的形状呈现到我们的网页上。

建立 (Setup)

All we need to start is an HTML page with a canvas tag and a JavaScript file to manipulate it with.

我们需要启动的只是一个带有canvas标记HTML页面和一个用于对其进行操作JavaScript文件。

index.html
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge"/>
    <title>HTML Canvas</title>
  </head>
  <body>

    <canvas></canvas>

  </body>
  <script src="./canvas.js"></script>
</html>

With our canvas element in place, we now need to create a new variable with it and a canvas context, which adds a bunch of functionality onto our canvas. To keep things simple we’ll stick with 2D shapes, but with the webgl context, 3D is also possible.

放置好canvas元素后,我们现在需要使用它创建一个新变量和一个canvas上下文,这将为我们的canvas增加很多功能。 为了使事情简单,我们将坚持使用2D形状,但是在webgl上下文中,3D也是可行的。

For our example we’ll need our canvas to be fullscreen but setting the size using CSS creates a strange blurry effect, which we obviously don’t want, so we’ll have to set it here.

对于我们的示例,我们需要使画布全屏显示,但是使用CSS设置尺寸会产生奇怪的模糊效果,这显然是我们所不希望的,因此我们必须在此处进行设置。

canvas.js
canvas.js
// getting a reference to our HTML element
const canvas = document.querySelector('canvas')

// initiating 2D context on it
const c = canvas.getContext('2d')

addEventListener('resize', () => {
  canvas.width = innerWidth
  canvas.height = innerHeight
})

长方形 (Rectangles)

To draw rectangles, on our context variable (c), we can start adding what we want, measured in pixels:

要绘制矩形,请在上下文变量( c )上开始添加所需像素(以像素为单位):

  • rect(x-axis, y-axis, width, height): Sets the location and dimensions of our rectangle, and needs to be called before stroke or fill.

    rect(x-axis, y-axis, width, height) :设置矩形的位置和尺寸,需要在strokefill之前调用。

  • stroke: Renders an outline of everything before it.

    stroke :渲染之前所有内容的轮廓。

  • fill: Renders the whole shape as a solid color.

    fill :将整个形状呈现为纯色。

  • strokeStyle and fillStyle: Sets the outline and shape color. They are not functions like the others and need to be assigned a string.

    strokeStylefillStyle :设置轮廓和形状颜色。 它们与其他函数不同,需要分配一个字符串。

  • strokeRect and fillRect: Same as stroke and fill but only for that item, works the same as rect.

    strokeRectfillRect :与strokefill相同,但仅适用于该项目,与rect相同。

  • clearRect(x-axis, y-axis, width, height): Clears everything inside of a certain area. Very useful when we get into animations where we’re constantly rendering new elements and don’t want the old ones to stick around.

    clearRect(x-axis, y-axis, width, height) :清除特定区域内的所有内容。 当我们进入不断渲染新元素而又不想让旧元素停留的动画时,此功能非常有用。

canvas.js
canvas.js
c.strokeStyle = 'white'
c.fillStyle = 'blue'
c.rect(100, 20, 150, 100)
c.stroke()
c.fill()

c.fillStyle = 'red'
c.fillRect(400, 500, 300, 250)

// Uncomment to remove the first two blocks
// c.clearRect(0, 0, canvas.width, canvas.height)
c.fillStyle = 'green'
c.fillRect(1500, 500, 300, 250)

线数 (Lines)

  • beginPath: Starts a new Line

    beginPath :开始新的一行

  • stroke: Renders the line

    stroke :渲染线

  • moveTo(x-axis, y-axis): Sets the starting point

    moveTo(x-axis, y-axis) :设置起点

  • lineTo(x-axis, y-axis): Renders a line from the previous endpoint

    lineTo(x-axis, y-axis) :从上一个端点渲染一条线

  • lineWidth: Set the line’s thickness

    lineWidth :设置线的粗细

And here are a few examples where we draw some lines:

以下是一些绘制一些线的示例:

// Just a basic line
c.beginPath()
c.moveTo(40, 250)
c.lineTo(200, 500)
c.strokeStyle = 'red'
c.stroke()

// Draw the letter M
c.beginPath()
c.moveTo(1500, 700)
c.lineTo(1600, 450)
c.lineTo(1700, 700)
c.lineTo(1800, 450)
c.lineTo(1900, 700)
c.strokeStyle = 'blue'
c.stroke()

// Let's now draw a house
c.lineWidth = 10
c.strokeStyle = 'red'
c.fillStyle = 'red'

// Walls 
c.strokeRect(800, 500, 300, 200)

// Door
c.fillRect(925, 600, 50, 100)

// Roof 
c.beginPath()
c.moveTo(700, 500)
c.lineTo(1200, 500)
c.lineTo(950, 300)
c.lineTo(700, 500)
c.stroke()

(Circles)

The only method we really need for drawing circles is arc. The angles are taken in radians and not degrees so for our end-angle we can just use Math.PI * 2, since that’s equal to 360 degrees, and the starting angle can be left at 0. We’re not going to need to specify a value for counterclockwise, so we can just leave it off since it defaults to false.

我们真正需要绘制圆的唯一方法是arc 。 角度以弧度而不是度为单位,因此对于我们的端角,我们可以仅使用Math.PI * 2 ,因为它等于360度,起始角度可以保留为0。我们不需要为counterclockwise指定一个值,因此我们可以将其保留为默认值,因为它默认为false。

  • arc(x, y, radius, starting-angle, end-angle, counterclockwise (boolean))

    arc(x, y, radius, starting-angle, end-angle, counterclockwise (boolean))

canvas.js
canvas.js
c.lineWidth = 5
c.beginPath()
c.arc(400, 400, 50, 0, Math.PI * 2)
c.stroke()

二次曲线和贝塞尔曲线 (Quadratic and Bezier Curves)

If you’ve ever used graphic design tools like Photoshop or Affinity Designer, these will seem very similar to some of their line tools.

如果您曾经使用过Photoshop或Affinity Designer之类的图形设计工具,则这些工具似乎与他们的某些线条工具非常相似。

Essentially, quadratic and bezier curves are just free form lines with different methods of control. Quadratic curves are simpler in that they just have a start, endpoint, and what’s known as the control point, which acts as a handle for curving the line. You can see a wonderful interactive example here. Bezier curves, on the other hand, have two control points, at each end of the curve for more complex shapes. Another great example here.

本质上,二次曲线和贝塞尔曲线只是具有不同控制方法的自由形式的线。 二次曲线比较简单,因为它们只有起点,终点和所谓的控制点,即控制曲线的句柄。 您可以在此处看到一个精彩的交互式示例。 另一方面,贝塞尔曲线在曲线的两端具有两个控制点,可用于更复杂的形状。 这里的另一个很好的例子。

  • quadraticCurveTo(controlPoint-x, controlPoint-y, endpoint-x, endpoint-y)

    quadraticCurveTo(controlPoint-x, controlPoint-y, endpoint-x, endpoint-y)

  • bezierCurveTo(startControlPoint-x, startControlPoint-y, endControlPoint-x, endControlPoint-y, endpoint-x, endpoint-y)

    bezierCurveTo(startControlPoint-x, startControlPoint-y, endControlPoint-x, endControlPoint-y, endpoint-x, endpoint-y)

And some examples:

还有一些例子:

canvas.js
canvas.js
c.lineWidth = 5
c.strokeStyle = 'white'

c.beginPath()
c.moveTo(400, 400)
c.lineTo(400, 300)
c.quadraticCurveTo(450, 250, 500, 300)
c.lineTo(500, 400)
c.stroke()

c.beginPath()
c.moveTo(800, 400);
c.bezierCurveTo(800, 150, 1200, 700, 1200, 400);
c.stroke()

文本 (Text)

Text works very similarly to rectangles with a few CSS-like options for styling:

文本的工作原理与矩形非常相似,但矩形的样式选项却很少:

  • fillText(text, x, y)

    fillText(text, x, y)

  • strokeText(text, x, y)

    strokeText(text, x, y)

  • font: Takes a string with the size in pixels and font family; like ’60px Times-New-Roman’.

    font:采用大小以像素和字体系列为单位的字符串; 例如“ 60px Times-New-Roman ”。

  • textAlign: Takes a string with the same options as its CSS counterpart; start, end, left, right, and center.

    textAlign :采用与CSS对应选项相同的字符串; startendleftrightcenter

canvas.js
canvas.js
c.font = '60px Times-New-Roman'
c.fillText("Hello World", 600, 500)
c.strokeText('Hello World', 1200, 500)

结论 (Conclusion)

While there is still an enormous amount that can be done with HTML canvas like animations and interactivity, hopefully this was a good first introduction to some of its possibilities.

尽管使用HTML画布(如动画和交互性)仍可以完成大量工作,但希望这是对它的某些可能性的很好的首次介绍。

翻译自: https://www.digitalocean.com/community/tutorials/js-drawing-shapes-canvas-api

canvas 绘制图片形状

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值