简体   繁体   中英

How to draw coordinates in JavaScript Canvas

I want to draw polynomials like 4x^2+3x+4 with JavaScript and Canvas. For this I wrote a function in JavaScript that calculates these values of this polynomials and return 2000 x/y coordinates in Interval [-20, +20]. How i can draw this coordinates in Canvas?

Thank you

Something like the following code may help you. Within it, a canvas is created, the width and height is set to 40 (to simulate -20 to 20), then the points, placed in an array, are combined into Path2Dpath data . 20 is added to the x coordinates, because a canvas displays only coordinates on the positive plane, and the y coordinates are made negative and 40 is added to them because [0, 0] on a canvas is the top left, and positive y coordinates go down instead of up.

 document.addEventListener('DOMContentLoaded', () => { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = 40; canvas.height = 40; var points = []; for(var i = -20; i <= 20; i+= 0.01) { points.push(i+20, -(4*i**2+3*i+4)+40); } var path = new Path2D('M '+points.shift()+' '+points.shift()+' L '+points.join(' ')); context.stroke(path); document.body.append(canvas); });

I would recommend, however, using an SVG instead -- if possible. It's a very similar idea, but it may produce a higher quality result. In this example, an svg element and a path element are created, the SVG's viewBox is set to -20 to 20 on both axis, then the same path data in the previous example is added to the path's 'd' attribute. X and Y aren't changed as much because the SVG's viewBox was changed, but Y is still made negative -- for the same reason as the canvas solution.

 document.addEventListener('DOMContentLoaded', () => { var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); var path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); var points = []; for(var i = -20; i <= 20; i+= 0.01) { points.push(i, -(4*i**2+3*i+4)); } svg.setAttribute('viewBox', '-20 -20 40 40'); path.setAttribute('d', 'M '+points.shift()+' '+points.shift()+' L '+points.join(' ')); path.setAttribute('fill', 'transparent'); path.setAttribute('stroke', 'black'); svg.append(path); document.body.append(svg); });

You might have stored your coordinates in an array like the following: [[x, y], [x, y]]. If so, this solution will work if array.flat() is used to convert the array to [x, y, x, y].

I may not have properly explained these code snippets, but hopefully this answer is useful to you.

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