首页 > 解决方案 > HTML5 Canvas:使用构造函数创建复杂的 Canvas 形状

问题描述

我目前正在开发一个 HTML5 Canvas 项目(我在这里写了一个单独的问题)。我认为我面临的问题的解决方案之一是为路径创建一个引用(保存为对象),并使用该方法ispointinpath检查我的鼠标位置是否在路径内 - 如果不是,它重置游戏。

我尝试为复杂的路径形状创建构造函数。以下是复杂形状作为原始代码的样子:

var canvas = document.querySelector('canvas');

// returning a drawing context to a variable 'c'
// allows you to draw 2d elements
var c = canvas.getContext('2d'); 

  canvas.width = 1000;
  canvas.height = 700;
  canvas.style.width = 1000;
  canvas.style.height = 700;
  
        c.beginPath();
        c.moveTo(350, 650); //start
        c.lineTo(350, 200);
        c.lineTo(900, 200);
        c.lineTo(900, 250);
        c.lineTo(700, 250);
        c.lineTo(600, 250);
        c.lineTo(600, 650);
        c.fillStyle = "#C1EEFF";
        c.fill();
<canvas></canvas>

这是我尝试制作的构造函数的样子:

var canvas = document.querySelector('canvas');

// returning a drawing context to a variable 'c'
// allows you to draw 2d elements
var c = canvas.getContext('2d');

  canvas.width = 1000;
  canvas.height = 700;
  canvas.style.width = 1000;
  canvas.style.height = 700;
  

var points = [(350, 200), (900, 200), (900, 250), (700, 250), (600, 250), (600, 650)];

function Path(startX, startY, array, color){
      c.beginPath();
      c.moveTo(startX, startY);

      // For however many element pairs in the array, create a lineTo statement
      for(i = 1; i < array.length; i++){
        c.lineTo(array[i][0], array[i][1]);
      }
  
      c.fillStyle = color;
      c.fill();
}

var blue = new Path(350, 200, points, '#C1EEFF');
<canvas></canvas>

它似乎不起作用。有谁知道这是为什么?另外,对于我正在尝试做的事情,最好的语法是什么?

标签: javascriptcanvasconstructorhtml5-canvas

解决方案


您似乎正在尝试使用此语法 array[i][0], array[i][1] 访问您的数组坐标,但是您的数组不是数组数组,而是括号数组。我没有时间玩它,但试着把它变成一个数组数组,这样你就可以访问元素 [0] 和 [1]。

[[350, 200], [400, 250]] 等

编辑:我正在提供一个 ES6 类来创建您的地图。这只是此处提供的其他选项之上的另一个选项。

const canvas = document.querySelector('canvas');
const c = canvas.getContext('2d');
canvas.width = 1000;
canvas.height = 700;
 
let points = [[300, 400], [400, 400], [400, 350], [400, 250], [700, 250], [700, 150], [750, 150], [750, 50], [775, 50], [775, 175], [725, 175], [725, 400], [500, 400], [500, 500], [500, 650], [300, 650] ];
let points2 = [[750, 50], [775, 50], [775, 100], [750, 100]];

class Map {
  constructor(start_x, start_y, arr, c) {
    this.start_x = start_x;
    this.start_y = start_y;
    this.arr = arr;
    this.color = c;
  }
  draw() {
    c.beginPath();
    c.moveTo(this.start_x, this.start_y); //start
    this.arr.forEach(point => c.lineTo(point[0], point[1]));
    c.fillStyle = this.color;
    c.fill();
    c.closePath(); 
  }
}
let map1 = new Map(300, 650, points, 'blue');
let map1Finish = new Map(750, 100, points2, 'red');
map1.draw();
map1Finish.draw();

推荐阅读