简体   繁体   中英

Draw canvas shape

I need to draw the following canvas shape. I can't figure out how to make it. I tried to use lineTo() but I'm having a hard time positioning those line segments. Moreover it doesn't take a curve shape.

在此处输入图片说明

The <canvas> size should be equal to 600x450. Thanks in advance.

You can use method bezierCurveTo() :

The CanvasRenderingContext2D.bezierCurveTo() method of the Canvas 2D API adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using moveTo() before creating the Bézier curve.

Here is a basic example:

 const canvas = document.getElementById("opCanvas"); const ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.lineWidth =5; ctx.strokeStyle ='orange'; ctx.moveTo(150,0); ctx.bezierCurveTo(0,125,300,175,150,300); ctx.stroke(); 
 <canvas id ="opCanvas" width="600" height ="450"> 

Here is a helper tool for doing that: http://www.victoriakirst.com/beziertool/

Using the bezier curve as Cezar Augusto demonstrated can be combined with the canvas 2D API's dash settings. setLineDash(array) create a dashed line from the array argument. lineDashOffset is the offset to where to start the sequence of dashes and gaps

  var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var w = canvas.width = innerWidth - 20; var h = canvas.height = innerHeight - 20; document.body.appendChild(canvas) ctx.setLineDash([14, 16]); ctx.lineDashOffset = 2; ctx.lineWidth = 4; ctx.setTransform(1,0,0,1,0,h/2); ctx.beginPath(); ctx.moveTo(0,0); ctx.bezierCurveTo(w / 2, h, w / 2, -h, w, 0); ctx.stroke(); 

setLineDash takes an array of numbers that represent the number of pixels for the dash then space and so on. If the array length is odd it is repeated to repeat at the start of a dash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM