我有以下代码应该在图像中绘制线条。我的代码是:
const { createCanvas } = require('canvas')
const fs = require('fs')
const width = 500
const height = 600
const canvas = createCanvas(width, height)
const ctx = canvas.getContext('2d')
ctx.fillStyle = '#fff'
ctx.fillRect(0, 0, width, height)
ctx.beginPath();
ctx.moveTo(0, 0);
let test = ['53.266179561615,54.9594819545746', '53.266179561615,54.9594819545746']
for (let index = 0; index < test.length; index++) {
let coordinates = test[index]
ctx.lineTo(coordinates)
ctx.stroke()
}
const buffer = canvas.toBuffer('image/png')
fs.writeFileSync('./image.png', buffer)
如果我编写ctx.lineto(53.266179561615,54.9594819545746)
,它实际上可以工作。但是我的数组很长并且来自一个输入。
let test = ['53.266179561615,54.9594819545746', '53.266179561615,54.9594819545746']
是字符串数组,而ctx.lineTo(x,y)
方法以两个数字作为参数。在您的代码中会发生以下情况:
for (let index = 0; index < test.length; index++) {
let coordinates = test[index]
// coordinates is now '53.266179561615,54.9594819545746'
ctx.lineTo(coordinates)
// you call ctx.lineTo('53.266179561615,54.9594819545746'), notice the qoutes.
// That is a single argument, a string.
...
您可能希望使用坐标数组,这样就可以正确调用函数。
像这样:
let coordinates = [[53.266179561615,54.9594819545746], [53.266179561615,54.9594819545746]];
for (let index = 0; index < coordinates.length; index++) {
let c = coordinates[index]
ctx.lineTo(c[0], c[1])
ctx.stroke()
}