本文介绍了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>
Here's what it looks like as a constructor function that I tried to make:
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>
它似乎不起作用.有人知道为什么吗?另外,什么是我要尝试的最佳语法?
推荐答案
我正在提供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();
这篇关于HTML5 Canvas:使用构造函数创建复杂的Canvas形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!